<?php

namespace app\app\controller;


use Alipay\EasySDK\Kernel\Config;
use app\common\controller\Homebase;
use EasyWeChat\Factory;
use think\Db;
use util\File;
use function Symfony\Component\String\u;
use Alipay\EasySDK\Kernel\Factory as AlipayFactory;

class WxUser extends Homebase
{
    protected $openid;
    protected $memberInfo;
    protected $memberId;
    protected $role;

    protected function initialize()
    {
        parent::initialize();
        $authorization = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
        if (empty($authorization)) {
            responseJson(-100, '请先登录');
        }
        $this->openid = $authorization;

        /*        $user = Db::name('member')->where('openid', '=', $this->openid)*/
        $user = Db::name('member')->where('mobile', '=', $this->openid)
            ->field('id,openid,nickname,avatarUrl,mobile,status,fraction,code_url,invite_id,role,is_fx,zfb_open_id')->find();
        if (empty($user)) {
            responseJson(-100, '登录信息有误');
        }
        if ($user['status'] == 0) {
            msg(-200, '用户已冻结', $user);
        }
        if (!strpos($user['avatarUrl'], 'ttp')) {
            $user['avatarUrl'] = config('wechat.url') . $user['avatarUrl'];
        }
        $this->memberInfo = $user;
        $this->memberId = $user['id'];
    }

    /**
     * 获取用户信息
     */
    public function getMemberInfo()
    {
        $this->memberInfo['package_num'] = Db::name('member_package')
            ->where(['member_id' => $this->memberId, 'is_del' => 0])
            ->where('end_time', '>=', time())
            ->count();
        $this->memberInfo['vip_num'] = Db::name('mcard_list')
            ->where(['member_id' => $this->memberId, 'is_expire' => 0, 'is_del' => 0])
            ->where('end_time', '>=', time())
            ->count();
        //会员二维码
        if (!$this->memberInfo['code_url']) {
            $code_url = qrcode($this->memberId, '');
            Db::name('member')->update([
                'id' => $this->memberId,
                'code_url' => $code_url
            ]);
        }
        msg(0, '查询成功', $this->memberInfo);
    }

    /**
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * 修改用户信息
     */
    public function updateUserinfo()
    {
        $data = $this->request->param();
        $update_data = array();
        if (isset($data['mobile']) && $data['mobile']) {
            $update_data['mobile'] = $data['mobile'];
        }
        if (isset($data['nickname']) && $data['nickname']) {
            $update_data['nickname'] = $data['nickname'];
        }
        if (isset($data['avatarUrl']) && $data['avatarUrl']) {
            $update_data['avatarUrl'] = $data['avatarUrl'];
        }
        $stmt = Db::name('member')
            ->where('mobile', $this->openid)
            ->update($update_data);
        if ($stmt) {
            msg(0, "修改成功", []);
        } else {
            msg(-1, "修改失败", []);
        }
    }

    //我的套餐列表
    public function getMemberPackageList()
    {
        $where[] = ['is_del', '=', 0];
        $where[] = ['member_id', '=', $this->memberId];
        $where[] = ['create_time', '<=', time()];
        $where[] = ['end_time', '>=', time()];
        $data = Db::name('member_package')
            ->where($where)
//            ->where(['member_id' => $this->memberId, 'is_del' => 0])
            ->order('create_time desc')
            ->select();
        msg(0, "查询成功", $data);
    }

    //我的套餐列表详情
    public function getMemberPackageServer()
    {
        $data = $this->request->param();
        $data_list = Db::name('member_package_server')->where([
            ['mp_id', '=', $data['id']],
            ['server_num', '>', 0]
        ])->select();
        foreach ($data_list as $k => $v) {
            $server_info = Db::name('server')->find($v['server_id']);
            $server_info['tag'] = explode(',', $server_info['tag']);
            $data_list[$k]['server_info'] = $server_info;
        }
        msg(0, "查询成功", $data_list);
    }

    //给用户赠送套餐
    public function giveMemberPackage()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            $package_id = $data['package_id'];

            $package_data = Db::name('package')
                ->where(['id' => $package_id, 'is_del' => 0])
                ->find();
            if (!$package_data) {
                msg(-1, '套餐不存在', []);
            }
            $package_server = Db::name('package_server')->where(['package_id' => $package_id])->select();
            $member_package_data = array(
                'member_id' => $this->memberId,
                'package_name' => $package_data['name'],
                'package_id' => $package_id,
                'create_time' => time(),
                'end_time' => time() + ($package_data['day_num'] * 86400)
            );
            $mp_id = Db::name('member_package')->insertGetId($member_package_data);
            $member_package_server_data = array();
            foreach ($package_server as $k => $v) {
                $time = time();
                $member_package_server_data[] = [
                    'mp_id' => $mp_id,
                    'server_id' => $v['server_id'],
                    'member_id' => $this->memberId,
                    'server_num' => $v['num'],
                    'num' => $v['num'],
                    'create_time' => $time
                ];
            }
            Db::name('member_package_server')->insertAll($member_package_server_data);
            Db::commit();
            msg(0, '查询成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //获取就诊人列表
    public function getPatientList()
    {
        $data_list = Db::name('patient')
            ->where(['member_id' => $this->memberId, 'is_del' => 0])
            ->select();
        foreach ($data_list as $k => $v) {
            $data_list[$k]['checked'] = false;
            if ($v['relationship'] == '本人') {
                $data_list[$k]['checked'] == true;
            }
        }
        msg(0, '查询成功', $data_list);
    }

    //通过id获取就诊人信息
    public function getPatientById()
    {
        $data = $this->request->param();
        $data_list = Db::name('patient')->find($data['id']);
        msg(0, '查询成功', $data_list);
    }

    //创建就诊人
    public function createPatient()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            $insert_data = array(
                'member_id' => $this->memberId,
                'name' => $data['name'],
                'phone' => $data['phone'],
                'sex' => $data['sex'],
                'age' => $data['age'],
                'relationship' => $data['relationship'],
                'past_medical_history' => $data['past_medical_history'],
                'history_of_allergies' => $data['history_of_allergies'],
            );
            $insert_id = Db::name('patient')->insertGetId($insert_data);
            Db::commit();
            msg(0, '创建成功', $insert_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //修改就诊人
    public function updatePatient()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            $insert_data = array(
                'id' => $data['id'],
                'name' => $data['name'],
                'phone' => $data['phone'],
                'sex' => $data['sex'],
                'age' => $data['age'],
                'relationship' => $data['relationship'],
                'past_medical_history' => $data['past_medical_history'],
                'history_of_allergies' => $data['history_of_allergies'],
            );
            $insert_id = Db::name('patient')->update($insert_data);
            Db::commit();
            msg(0, '修改成功', $insert_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //删除就诊人
    public function delPatient()
    {
        $data = $this->request->param();
        $del_data = array(
            'id' => $data['id'],
            'is_del' => 1
        );
        Db::name('patient')->update($del_data);
        msg(0, '修改成功', '');
    }

    //我的会员卡列表 todo 增加定时任务 设置会员卡过期
    public function mcardList()
    {
        $data_list = Db::name('mcard')
            ->where(['is_del' => 0, 'status' => 1])
            ->order('sort desc')
            ->select();
        foreach ($data_list as $k => $v) {
            $desc_list = Db::name('mcard_desc')
                ->where(['mcid' => $v['id'], 'status' => 1])
                ->order('sort desc')
                ->select();
            $is_able = Db::name('mcard_list')
                ->where(['is_del' => 0, 'mcard_id' => $v['id'], 'member_id' => $this->memberId, 'is_expire' => 0])
                ->find();
            $is_able ? $data_list[$k]['is_able'] = 1 : $data_list[$k]['is_able'] = 0;
            $data_list[$k]['desc_list'] = $desc_list;
        }
        msg(0, '查询成功', $data_list);
    }

    //会员卡权益列表
    public function mcardDetail2()
    {
        $data = $this->request->param();
        $desc_list = Db::name('mcard_desc')
            ->where(['mcid' => $data['id'], 'status' => 1])
            ->order('sort desc')
            ->select();
        msg(0, '查询成功', $desc_list);
    }

    public function getmcardDetail()
    {
        $data = $this->request->param();
        $return_data = Db::name('mcard')->find($data['id']);
        msg(0, '查询成功', $return_data);
    }

    //激活会员卡
    public function activeCard()
    {
        $data = $this->request->param();
        $mcard_id = $data['mcard_id'];
        $no = $data['no'];
        $secret = $data['secret'];
        Db::startTrans();
        try {
            $mcard_list_info = Db::name('mcard_list')
                ->where(['mcard_id' => $mcard_id, 'secret' => $secret, 'is_del' => 0, 'is_expire' => 0])
//                ->where(['mcard_id' => $mcard_id, 'no' => $no, 'secret' => $secret, 'is_del' => 0, 'is_expire' => 0])
                ->find();
            if (!$mcard_list_info) {
                msg(-1, '卡号信息错误', '');
            }
            if ($mcard_list_info['status'] == 1) {
                msg(-2, '卡号已激活', '');
            }
            //判断用户是否已激活
            activeCard($mcard_list_info['id'], $this->memberId);
            Db::commit();
            msg(0, '激活成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }
    //后台 会员卡到期时间 会员卡列表
    //获取积分商品类型
    public function getGoodsCate2()
    {
        $data_list = Db::name('goods_cate')
            ->where(['is_del' => 0, 'status' => 1])
            ->order('sort desc')
            ->select();
        msg(0, '查询成功', $data_list);
    }


    //积分兑换
    public function fractionExchange()
    {
        $data = $this->request->param();
        $goods_info = Db::name('goods')->where(['id' => $data['id']])->find();
        if (!$goods_info) {
            msg(-1, '商品不存在', '');
        }
        Db::startTrans();
        try {
            //判断积分 使用积分  积分记录
            if ($goods_info['points'] > $this->memberInfo['fraction']) {
                msg(-1, '积分不足', '');
            }
            //增加订单 增加优惠卷 增加服务
            //$object_cate 兑换商品类型 0陪诊 1医疗用品 2优惠卷
            //type1签到 2兑换 3下订单 4其他
            $insert_goods_order_data = array(
                'no' => GetOrderSN(2),
                'goods_id' => $data['id'],
                'member_id' => $this->memberId,
                'create_time' => time(),
                'points' => $goods_info['points'],
                'goods_cate' => $goods_info['goods_cate'],
                'goods_name' => $goods_info['name'],
                'goods_img' => $goods_info['img']
            );
            //0陪诊 1医疗用品 2优惠卷
            if ($goods_info['goods_cate'] == 1) {
                $insert_goods_order_data['is_express'] = 1;
                $insert_goods_order_data['realname'] = $data['people'];
                $insert_goods_order_data['telphone'] = $data['phone'];
                $insert_goods_order_data['province'] = $data['province'];
                $insert_goods_order_data['city'] = $data['city'];
                $insert_goods_order_data['area'] = $data['area'];
                $insert_goods_order_data['address'] = $data['address'];
            }
            if ($goods_info['goods_cate'] == 0) {
                $server_info = Db::name('server')->find($goods_info['object_id']);
                $insert_goods_order_data['goods_name'] = $server_info['name'];
                $insert_goods_order_data['goods_img'] = $server_info['bc_img'];
                $insert_goods_order_data['status'] = 3;
                //增加陪诊服务
                $server_info = Db::name('server')->find($goods_info['object_id']);
                $result_id = getServer($this->memberId, $server_info);
                $insert_goods_order_data['create_id'] = $result_id;
            }
            if ($goods_info['goods_cate'] == 2) {
                $coupons_info = Db::name('coupons')->find($goods_info['object_id']);
                $insert_goods_order_data['coupons_money'] = $coupons_info['value'];
                $insert_goods_order_data['goods_img'] = config('site.shop_coupons_img');
                $insert_goods_order_data['status'] = 3;
                //增加优惠卷
                $coupon_info = Db::name('coupons')->find($goods_info['object_id']);
                $result_id = getCoupons($this->memberId, $coupon_info, 2);
                $insert_goods_order_data['create_id'] = $result_id;
            }
            $goods_order_id = Db::name('goods_order')->insertGetId($insert_goods_order_data);
            //兑换数量
            Db::name('goods')->where('id', '=', $data['id'])->setInc('salenum');
//            Db::name('goods')->where('id','=',$data['id'])->setDec('inventory');
            addFraction($this->memberId,
                $goods_info['points'],
                '积分兑换',
                2,
                2,
                $goods_info['goods_cate'],
                $goods_order_id);
            Db::commit();
            msg(0, '查询成功', $goods_order_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //积分明细
    public function fractionHistory()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $type = $data['type'];
        $where[] = ['member_id', '=', $this->memberId];
        //0全部 1收入 2支出  类型 1签到 2兑换 3下订单 4其他'
        if ($type == 1) {
            $where[] = ['type', '=', 3];
        } elseif ($type == 2) {
            $where[] = ['type', '=', 2];
        }
        $data_list = Db::name('fraction_record')->where($where)->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                return $item;
            });
        msg(0, '查询成功', $data_list);
    }

    //积分兑换记录
    public function exchangeHistory()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['is_del', '=', 0];
        $where[] = ['member_id', '=', $this->memberId];
        $data_list = Db::name('goods_order')
            ->where($where)
            ->order('create_time desc')
            ->page($page, $length)
            ->select();
        foreach ($data_list as $k => $v) {
            $data_list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
        }
        msg(0, '查询成功', $data_list);
    }

    //获取兑换详情
    public function exchangeOrderDetail()
    {
        $data = $this->request->param();
        $return_data = Db::name('goods_order')->find($data['id']);
        $return_data['create_time'] = date('Y-m-d H:i:s', $return_data['create_time']);
        msg(0, '查询成功', $return_data);
    }

    //todo 会员卡不能重复购买 套餐不能重复购买

    //获取套餐列表
    public function getPackageList2()
    {
        $data = $this->request->param();
        $PackageList = Db::name('package')
            ->where(['is_del' => 0, 'status' => 1])
            ->order('sort desc')->select();
        foreach ($PackageList as $k => $v) {
            $server_count = Db::name('package_server')->where([
                'package_id' => $v['id']
            ])->count();
            $PackageList[$k]['server_count'] = $server_count;
        }
        msg(0, '查询成功', $PackageList);
    }

    //获取套餐详情
    public function getPackageDetail()
    {
        $data = $this->request->param();
        $package_id = $data['id'];
        $package_data = Db::name('package')->find($package_id);
        $package_server = Db::name('package_server')
            ->where([
                ['package_id', '=', $package_id],
                ['num', '>', 0],
            ])
            ->select();
        $package_data['server_count'] = count($package_server);
        foreach ($package_server as $k => $v) {
            $server_info = Db::name('server')->find($v['server_id']);
            $server_info['tag'] = explode(',', $server_info['tag']);
            $package_server[$k]['server_info'] = $server_info;
        }
        $return_data['package_data'] = $package_data;
        $return_data['package_server'] = $package_server;
        msg(0, '查询成功', $return_data);
    }

    //获取我的会员卡列表
    public function getMyVipList()
    {
        $where[] = ['ml.is_del', '=', '0'];
        $where[] = ['ml.end_time', '>=', time()];
        $where[] = ['ml.member_id', '=', $this->memberId];
        $vipList = Db::name('mcard_list')
            ->alias('ml')
            ->join('mcard m', 'm.id=ml.mcard_id')
            ->field('ml.*,m.name as mname,m.img as m_img')
            ->where($where)
            ->order('create_time desc')
            ->select();
        msg(0, '查询成功', $vipList);
    }

    //获取我的会员卡详情
    public function getMyVipDetail()
    {
        $data = $this->request->param();
        $mcard_list_id = $data['id'];
        $where[] = ['ml.id', '=', $mcard_list_id];
        $vipDetail = Db::name('mcard_list')
            ->alias('ml')
            ->join('mcard m', 'm.id=ml.mcard_id')
            ->field('ml.*,m.name as mname,m.img as m_img')
            ->where($where)
            ->order('create_time desc')
            ->find();

        $member_package_server = Db::name('member_mcard_server')
            ->alias('mms')
            ->where([
                ['mms.server_num', '>', 0],
                ['mms.mcard_list_id', '=', $mcard_list_id],
            ])
            ->join('server s', 'mms.server_id=s.id')
            ->field('mms.*,s.name,s.desc,s.bc_img,s.price,s.tag')
            ->select();
        $vipDetail['server_count'] = count($member_package_server);
        foreach ($member_package_server as $k => $v) {
            $member_package_server[$k]['tag'] = explode(',', $v['tag']);
        }
        $return_data['vipDetail'] = $vipDetail;
        $return_data['member_mcard_server'] = $member_package_server;
        msg(0, '查询成功', $return_data);
    }

    //获取我的套餐列表
    public function getMyPackageList()
    {
        $where[] = ['mp.is_del', '=', 0];
        $where[] = ['mp.member_id', '=', $this->memberId];
        $where[] = ['mp.create_time', '<=', time()];
        $where[] = ['mp.end_time', '>=', time()];
        $MyPackageList = Db::name('member_package')
            ->alias('mp')
            ->join('package p', 'mp.package_id=p.id')
            ->field('mp.*,p.name,p.price,p.desc,p.img,p.sale_num')
            ->order('mp.create_time desc')
            ->where($where)
            ->select();
        foreach ($MyPackageList as $k => $v) {
            $server_count = Db::name('package_server')->where([
                'package_id' => $v['package_id']
            ])->count();
            $MyPackageList[$k]['server_count'] = $server_count;
        }
        msg(0, '查询成功', $MyPackageList);
    }

    //获取我的套餐详情
    public function getMyPackageDetail()
    {
        $data = $this->request->param();
        $member_package_id = $data['id'];
        $member_package_info = Db::name('member_package')
            ->alias('mp')
            ->join('package p', 'mp.package_id=p.id')
            ->where('mp.id', '=', $member_package_id)
            ->find();
        $member_package_server = Db::name('member_package_server')
            ->alias('mps')
            ->where([
                ['mps.server_num', '>', 0],
                ['mps.mp_id', '=', $member_package_id],
            ])
            ->join('server s', 'mps.server_id=s.id')
            ->field('mps.*,s.name,s.desc,s.bc_img,s.price,s.tag')
            ->select();
        $member_package_info['server_count'] = count($member_package_server);
        foreach ($member_package_server as $k => $v) {
            $member_package_server[$k]['tag'] = explode(',', $v['tag']);
        }
        $return_data['package_data'] = $member_package_info;
        $return_data['package_server'] = $member_package_server;
        msg(0, '查询成功', $return_data);
    }

    //获取我的优惠卷列表
    public function getMemberCouponsList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $data_list = Db::name('member_coupons')->where([
            'status' => 1,
            'member_id' => $this->memberId,
            'is_del' => 0
        ])->order('create_time desc')->paginate($length, false, ['page' => $page])->each(function ($item) {
            //start_time    end_time
            $item['start_time'] = date('Y-m-d H:i:s', $item['start_time']);
            $item['end_time'] = date('Y-m-d H:i:s', $item['end_time']);
            $item['back_img_url'] = config('site.coupons_img2');
            $item['open'] = 0;
            return $item;
        });
        msg(0, '查询成功', $data_list);
    }
    //陪诊员状态 司机状态 分销状态
    //申请陪诊员
    public function createPz()
    {
        $data = $this->request->param();
        $pz_info = Db::name('pz')->where(['member_id' => $this->memberId, 'is_del' => 0])->find();
        if ($pz_info && $pz_info['status'] != 3) {
            msg(-1, '您已申请,请勿重复提交', '');
        }
        $insert_data = array(
            'member_id' => $this->memberId,
            'province' => $data['province'],
            'city' => $data['city'],
            'area' => $data['area'],
            'address' => $data['address'],
            'name' => $data['name'],
            'phone' => $data['phone'],
            'sf_id' => $data['sf_id'],
            'create_time' => time()
        );
        Db::startTrans();
        try {
            if ($pz_info && $pz_info['status'] == 3) {
                unset($insert_data['member_id']);
                $insert_data['status'] = 0;
                $insert_id = Db::name('pz')
                    ->where('is_del', '=', 0)
                    ->where('member_id', $this->memberId)
                    ->update($insert_data);
            } else {
                $insert_id = Db::name('pz')->insertGetId($insert_data);
            }
            Db::commit();
            msg(0, '查询成功', $insert_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //获取陪诊员审核状态
    public function getPzStatus()
    {
        $data = Db::name('pz')->where(['member_id' => $this->memberId, 'is_del' => 0])->find();
        if ($data) {
            if ($data['status'] == 1) {
                //返回数据
                msg(0, '申请已通过', $data);
            }
            if ($data['status'] == 3) {
                //返回数据
                msg(-3, '审核不通过', $data);
            }
            if ($data['status'] == 2) {
                //返回数据
                msg(-2, '账户冻结,请联系管理员', $data);
            }
            msg(1, '你已申请，等待审核', '');
        }
        msg(-1, '未申请', '');
    }

    //申请司机
    public function createDriver()
    {
        $data = $this->request->param();
        $Driver_info = Db::name('driver')->where([
            'member_id' => $this->memberId,
            'is_del' => 0
        ])->find();
        if ($Driver_info && $Driver_info['status'] != 3) {
            msg(-1, '已申请，请勿重复提交', '');
        }
        $insert_data = array(
            'member_id' => $this->memberId,
            'province' => $data['province'],
            'city' => $data['city'],
            'area' => $data['area'],
            'address' => $data['address'],
            'name' => $data['name'],
            'phone' => $data['phone'],
            'sf_id' => $data['sf_id'],
            'driver_img' => $data['driver_img'],
            'create_time' => time()
        );
        Db::startTrans();
        try {
            if ($Driver_info && $Driver_info['status'] == 3) {
                unset($insert_data['member_id']);
                $insert_data['status'] = 0;
                $insert_id = Db::name('driver')
                    ->where('is_del', '=', 0)
                    ->where('member_id', $this->memberId)
                    ->update($insert_data);
            } else {
                $insert_id = Db::name('driver')->insertGetId($insert_data);
            }
            Db::commit();
            msg(0, '查询成功', $insert_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //获取陪诊员审核状态
    public function getDriverStatus()
    {
        $data = Db::name('driver')->where(['member_id' => $this->memberId, 'is_del' => 0])->find();
        if ($data) {
            if ($data['status'] == 1) {
                //返回数据
                msg(0, '申请已通过', $data);
            }
            if ($data['status'] == 3) {
                //返回数据
                msg(-3, '审核不通过', $data);
            }
            if ($data['status'] == 2) {
                //返回数据
                msg(-2, '账户冻结,请联系管理员', $data);
            }
            msg(1, '你已申请，等待审核', '');
        }
        msg(-1, '未申请', '');
    }

    //申请分销
    public function createFx()
    {
        $data = $this->request->param();
        $fx_info = Db::name('fx')->where([
            'member_id' => $this->memberId,
            'is_del' => 0
        ])->find();
        if ($fx_info && $fx_info['status'] != 3) {
            msg(-1, '已申请,请勿重复提交', '');
        }
        $insert_data = array(
            'member_id' => $this->memberId,
            'province' => $data['province'],
            'city' => $data['city'],
            'area' => $data['area'],
            'address' => $data['address'],
            'name' => $data['name'],
            'phone' => $data['phone'],
            'sf_id' => $data['sf_id'],
            'create_time' => time()
        );
        Db::startTrans();
        try {
            if ($fx_info && $fx_info['status'] == 3) {
                unset($insert_data['member_id']);
                $insert_data['status'] = 0;
                $insert_id = Db::name('fx')
                    ->where('is_del', '=', 0)
                    ->where('member_id', $this->memberId)
                    ->update($insert_data);
            } else {
                $insert_id = Db::name('fx')->insertGetId($insert_data);
            }
            Db::commit();
            msg(0, '查询成功', $insert_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //获取分销员审核状态
    public function getFxStatus()
    {
        $data = Db::name('fx')
            ->where(['member_id' => $this->memberId, 'is_del' => 0])
            ->find();
        if ($data) {
            if ($data['status'] == 1) {
                //返回数据
                msg(0, '申请已通过', $data);
            }
            if ($data['status'] == 3) {
                //返回数据
                msg(-3, '审核不通过', $data);
            }
            if ($data['status'] == 2) {
                //返回数据
                msg(-2, '账户冻结,请联系管理员', $data);
            }
            msg(1, '你已申请，等待审核', '');
        }
        msg(-1, '未申请', '');
    }

    //获取订单开通省列表
    //获取医院、省 开通市列表
    //获取会员折扣
    public function getVipCount()
    {
        $where[] = ['is_del', '=', 0];
        $where[] = ['member_id', '=', $this->memberId];
        $where[] = ['is_expire', '=', 0];
        $member_vip = Db::name('mcard_list')
            ->where($where)
            ->order('discount desc')
            ->find();
        if ($member_vip) {
            return $member_vip['discount'];
        } else {
            return 0;
        }

    }

    public function getVipCount2()
    {
        msg(0, '查询完成', $this->getVipCount());
    }

    //获取订单可用优惠卷 //陪诊 导诊 司机订单都可以用
    public function getMemberCoupons2()
    {
        $data = $this->request->param();
        $where = array(
            'member_id' => $this->memberId,
            'status' => 1,
            'is_del' => 0
        );
        $time = time();
        $where2[] = ['start_time', '<=', $time];
        $where2[] = ['end_time', '>=', $time];
        $data_list = Db::name('member_coupons')
            ->where($where)
            ->where($where2)
            ->order('create_time desc')
            ->select();
        foreach ($data_list as $k => $v) {
            if ($v['min_amount'] <= $data['price']) {
                $data_list[$k]['is_able'] = 1;
            } else {
                $data_list[$k]['is_able'] = 0;
            }
        }
        msg(0, '查询成功', $data_list);
    }
    //支付方式 1微信支付 2套餐支付 3会员卡支付 4支付宝支付 5积分兑换卷支付
    //创建直接购买陪诊订单
    public function createServerOrder()
    {
        $data = $this->request->param();
        $city = $data['city'];
        $longitude = $data['longitude'];
        $latitude = $data['latitude'];
        //02-06-8:33
        $data['time'] = substr_replace($data['time'], ' ', 5, 1);
        $time = strtotime(date('Y') . '-' . $data['time']);
        $server_id = $data['server_id'];
        $insert_data = array(
            'order_no' => GetOrderSN(2),
            'hospital_id' => $data['hospital_id'],
            'department1' => $data['department1'],
            'department2' => $data['department2'],
            'time' => $time,
            'create_time' => time(),
            'member_id' => $this->memberId,
            'people' => $data['people'],
            'phone' => $data['phone'],
            'people2' => $data['people2'],
            'phone2' => $data['phone2'],
            'sex' => $data['sex'],
            'age' => $data['age'],
            'relationship' => $data['relationship'],
            'past_medical_history' => $data['past_medical_history'],
            'history_of_allergies' => $data['history_of_allergies'],
            'remark' => $data['remark'],
            'server_id' => $data['server_id'],
            'order_type' => 1,
            'is_car' => $data['is_car']
        );
        $server_info = Db::name('server')->find($server_id);
        $insert_data['price'] = getPrice($server_info['id'], $city);
        $insert_data['pay_money'] = $server_info['price'];

        $vip_count = $this->getVipCount();
        if ($vip_count) {
            $vip_discount = number_format($insert_data['pay_money'] * ($vip_count / 100), 2);
            $insert_data['pay_money'] = $insert_data['pay_money'] - $vip_discount;
            $insert_data['vip_discount'] = $vip_discount;
        }
        //使用优惠卷
        if (isset($data['mc_id']) && $data['mc_id']) {
            $coupons_where = array(
                'member_id' => $this->memberId,
                'id' => $data['mc_id'],
                'status' => 1,
                'is_del' => 0,
            );
            $member_coupons = Db::name('member_coupons')
                ->where($coupons_where)
                ->find();
            if (!$member_coupons) {
                msg(-1, '优惠券不存在', '');
            }
            if ($insert_data['pay_money'] < $member_coupons['min_amount']) {
                msg(-1, '优惠券不可用', '');
            }
            $insert_data['mc_id'] = $data['mc_id'];
            $insert_data['coupon_money'] = $member_coupons['value'];
            $insert_data['pay_money'] = number_format($insert_data['pay_money'] - $member_coupons['value'], 2);
        }
        if (config('site.web_one_price')) {
            $insert_data['pay_money'] = 0.01;
        }
        Db::startTrans();
        try {
            session_start();
            $lsterRequestTime = $_SESSION[$this->memberId . 'last_time'] ?? 0;
            $currenTRequestTime = time();
            $debounce = 5;
            if ($currenTRequestTime - $lsterRequestTime < $debounce) {
                msg(-1, '下单过频繁，请稍后下单', '');
            } else {
                $_SESSION[$this->memberId . 'last_time'] = $currenTRequestTime;
            }
            $order_id = Db::name('server_order')->insertGetId($insert_data);
            if ($data['is_car']) {
                $insert_data['is_car'] = 1;
                $data['go_time'] = substr_replace($data['go_time'], ' ', 5, 1);
                $go_time = strtotime(date('Y') . '-' . $data['go_time']);
                $insert_driver_data = array(
                    'order_no' => GetOrderSN(2),
                    'hospital_id' => $data['hospital_id'],
                    'create_time' => time(),
                    'go_time' => $go_time,
                    'order_type' => $data['order_type'],  //1单程 2返程 3往返
                    'member_id' => $this->memberId,
                    'people' => $data['people'],
                    'phone' => $data['phone'],
                    'people2' => $data['people2'],
                    'phone2' => $data['phone2'],
                    'age' => $data['age'],
                    'sex' => $data['sex'],
                    'relationship' => $data['relationship'],
                    'past_medical_history' => $data['past_medical_history'],
                    'remark' => $data['remark'],
                    'history_of_allergies' => $data['history_of_allergies'],
                    'route_type' => $data['route_type'],  //路线类型 1市外 2市内
                    'address' => $data['address']
                );
                $hospital_info = Db::name('hospital')->find($data['hospital_id']);
                $insert_driver_data['hospital_name'] = $hospital_info['name'];
                if ($data['route_type'] == 1) {
                    $insert_driver_data['province'] = $data['province'];
                    $insert_driver_data['city'] = $data['city2'];
                    $insert_driver_data['area'] = $data['area'];
                } else {
                    $insert_driver_data['province'] = $hospital_info['province'];
                    $insert_driver_data['city'] = $hospital_info['province'];
                    $insert_driver_data['area'] = $hospital_info['area'];
                }
                $price2 = $this->getRoutePrice2(
                    $data['hospital_id'],
                    $data['route_type'],
                    $data['province'],
                    $data['city2'],
                    $data['address'],
                    $data['order_type']
                );
                if ($price2 < 0) {
                    msg(-2, '路线不存在', '');
                }
                $insert_driver_data['price'] = $price2;
                $insert_driver_data['pay_money'] = $price2;
                if ($vip_count) {
                    $vip_discount = number_format($insert_driver_data['pay_money'] * ($vip_count / 100), 2);
                    $insert_driver_data['pay_money'] = $insert_driver_data['pay_money'] - $vip_discount;
                    $insert_driver_data['vip_discount'] = $vip_discount;
                }
                //server_order_id
                $insert_driver_data['server_order_id'] = $order_id;
                if (config('site.web_one_price')) {
                    $insert_driver_data['pay_money'] = 0.01;
                }
                $driver_order_id = Db::name('driver_order')->insertGetId($insert_driver_data);
                $server_order_update = array(
                    'id' => $order_id,
                    'driver_order_id' => (int)$driver_order_id
                );
                Db::name('server_order')->where('id', '=', $order_id)->update($server_order_update);
            }
            $order_info = Db::name('server_order')->find($order_id);
            $insert_data['id'] = (int)$order_id;
            if (isset($data['mc_id']) && $data['mc_id']) {
                //优惠券状态修改
                Db::name('member_coupons')->update(
                    [
                        'id' => $data['mc_id'],
                        'status' => 2,
                        'used_time' => time(),
                        'order_id' => $order_id
                    ]
                );
            }
            Db::commit();
            msg(0, '查询完成', $order_info);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //使用套餐、会员、服务创建订单
    public function createServerOrder3()
    {
        $data = $this->request->param();
        $city = $data['city'];
        $longitude = $data['longitude'];
        $latitude = $data['latitude'];
        $data['time'] = substr_replace($data['time'], ' ', 5, 1);
        $time = strtotime(date('Y') . '-' . $data['time']);
        $insert_data = array(
            'order_no' => GetOrderSN(2),
            'hospital_id' => $data['hospital_id'],
            'department1' => $data['department1'],
            'department2' => $data['department2'],
            'time' => $time,
            'create_time' => time(),
            'member_id' => $this->memberId,
            'people2' => $data['people2'],
            'phone2' => $data['phone2'],
            'people' => $data['people'],
            'phone' => $data['phone'],
            'sex' => $data['sex'],
            'age' => $data['age'],
            'relationship' => $data['relationship'],
            'past_medical_history' => $data['past_medical_history'],
            'history_of_allergies' => $data['history_of_allergies'],
            'remark' => $data['remark'],
            'order_type' => 1,
            'pay_type' => $data['pay_type'],
            'status' => 2,
            'pay_time' => time(),
            'pay_status' => 1,
        );
        //pay_type 2套餐支付 3会员卡支付 4支付宝支付 5积分兑换卷支付
        //卷id
        Db::startTrans();
        try {
            if ($data['pay_type'] == 2) {
                $c_info = Db::name('member_package_server')->find($data['id']);
                Db::name('member_package_server')->where('id', '=', $data['id'])->setDec('num');
            } elseif ($data['pay_type'] == 3) {
                $c_info = Db::name('member_mcard_server')->find($data['id']);
                Db::name('member_mcard_server')->where('id', '=', $data['id'])->setDec('num');
            } elseif ($data['pay_type'] == 5) {
                $c_info = Db::name('member_server')->find($data['id']);
                Db::name('member_server')->where('id', '=', $data['id'])->setDec('num');
            } else {
                msg(-1, '请选择正确支付方式', '');
            }
            if ($c_info['num'] <= 0) {
                msg(-2, '可使用次数不足', '');
            }
            $server_info = Db::name('server')->find($c_info['server_id']);
            $insert_data['server_id'] = $c_info['server_id'];
            $insert_data['exchange_id'] = $data['id'];
            $insert_data['price'] = $server_info['price'];
            $insert_data['pay_money'] = 0;
            session_start();
            $lsterRequestTime = $_SESSION[$this->memberId . 'last_time55'] ?? 0;
            $currenTRequestTime = time();
            $debounce = 5;
            if ($currenTRequestTime - $lsterRequestTime < $debounce) {
                msg(-1, '下单过频繁，请稍后下单', '');
            } else {
                $_SESSION[$this->memberId . 'last_time55'] = $currenTRequestTime;
            }
            $order_id = Db::name('server_order')->insertGetId($insert_data);
            $order_info = Db::name('server_order')->find($order_id);
            serverPaySuccess($order_info);
            $order_info = Db::name('server_order')->find($order_id);
            Db::commit();
            msg(0, '查询完成', $order_info);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //创建导诊订单
    public function createServerOrder2()
    {
        $data = $this->request->param();
        $city = $data['city'];
        $longitude = $data['longitude'];
        $latitude = $data['latitude'];
        $insert_data = array(
            'order_no' => GetOrderSN(2),
            'hospital_id' => $data['hospital_id'],
            'department1' => $data['department1'],
            'department2' => $data['department2'],
            'doctor_id' => $data['doctor_id'],
            'create_time' => time(),
            'member_id' => $this->memberId,
            'people2' => $data['people2'],
            'phone2' => $data['phone2'],
            'people' => $data['people'],
            'phone' => $data['phone'],
            'sex' => $data['sex'],
            'age' => $data['age'],
            'relationship' => $data['relationship'],
            'past_medical_history' => $data['past_medical_history'],
            'history_of_allergies' => $data['history_of_allergies'],
            'remark' => $data['remark'],
            'server_id' => 0,
            'order_type' => 2,
        );
        if (isset($data['y_time']) && $data['y_time']) {
            foreach ($data['y_time'] as $k => $v) {
                //'Y-m-d'
                $insert_data['y_time' . ($k + 1)] = strtotime($v['year'] . '-' . $v['month'] . '-' . $v['date']);
            }
        }

        $server_info = Db::name('server2')->find();
        $insert_data['price'] = $server_info['price'];
        $insert_data['pay_money'] = $server_info['price'];
        $vip_count = $this->getVipCount();
        if ($vip_count) {
            $vip_discount = number_format($insert_data['pay_money'] * ($vip_count / 100), 2);
            $insert_data['pay_money'] = $insert_data['pay_money'] - $vip_discount;
            $insert_data['vip_discount'] = $vip_discount;
        }
        //使用优惠卷
        if (isset($data['mc_id']) && $data['mc_id']) {
            $coupons_where = array(
                'member_id' => $this->memberId,
                'id' => $data['mc_id'],
                'status' => 1,
                'is_del' => 0,
            );
            $member_coupons = Db::name('member_coupons')
                ->where($coupons_where)
                ->find();
            if (!$member_coupons) {
                msg(-1, '优惠券不存在', '');
            }
            if ($insert_data['pay_money'] < $member_coupons['min_amount']) {
                msg(-1, '优惠券不可用', '');
            }
            $insert_data['mc_id'] = $data['mc_id'];
            $insert_data['coupon_money'] = $member_coupons['value'];
            $insert_data['pay_money'] = number_format($insert_data['pay_money'] - $member_coupons['value'], 2);
        }
        if (config('site.web_one_price')) {
            $insert_data['pay_money'] = 0.01;
        }
        Db::startTrans();
        try {
            session_start();
            $lsterRequestTime = $_SESSION[$this->memberId . 'last_time'] ?? 0;
            $currenTRequestTime = time();
            $debounce = 5;
            if ($currenTRequestTime - $lsterRequestTime < $debounce) {
                msg(-1, '下单过频繁，请稍后下单', '');
            } else {
                $_SESSION[$this->memberId . 'last_time'] = $currenTRequestTime;
            }
            $order_id = Db::name('server_order')->insertGetId($insert_data);
            $order_info = Db::name('server_order')->find($order_id);
            $insert_data['id'] = (int)$order_id;
            if (isset($data['mc_id']) && $data['mc_id']) {
                //优惠券状态修改
                Db::name('member_coupons')->update(
                    [
                        'id' => $data['mc_id'],
                        'status' => 2,
                        'used_time' => time(),
                        'order_id' => $order_id
                    ]
                );
            }
            Db::commit();
            msg(0, '查询完成', $order_info);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //导诊陪诊订单微信发起支付
    public function payServerOrder()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $type = $data['type'];   //1微信支付 2支付宝支付
        $order_data = Db::name('server_order')
            ->where('order_no', '=', $order_no)
            ->find();
        if (!$order_data) {
            msg(-1, '订单有误', '');
        }
        $userInfo = $this->memberInfo;
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $jssdk = $app->jssdk;
        //订单管理接送订单
        $pay_money = $order_data['pay_money'] * 100;
        if ($order_data['is_car'] == 1) {
            $driver_order = Db::name('driver_order')->where([
                'server_order_id' => $order_data['id']
            ])->find();
            if ($driver_order) {
                $pay_money = ($order_data['pay_money'] + $driver_order['pay_money']) * 100;
            }
        }
        if (config('site.web_one_price')) {
            $pay_money = 1;
//            if ($order_no['driver_order_id']){
//                $pay_money = 2;
//            }
        }
        $result = $app->order->unify([
            'body' => '陪诊服务',
            'out_trade_no' => $order_data['order_no'],
            'total_fee' => $pay_money,
            //           'total_fee' => 1,
//            'spbill_create_ip' => $orderdata['ip'], // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
//            'notify_url' => conf("lm", "url") . $config['notify_url'], // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $userInfo['openid'],
        ]);
        if ($result['return_code'] == "SUCCESS" && $result["result_code"] != "FAIL") {
            $config2 = $jssdk->bridgeConfig($result['prepay_id'], false);
            $result['msg'] = 'ok';
            $result['config'] = $config2;
            $result['order_no'] = $order_data['order_no'];
            $result['order_id'] = $order_data['id'];
            $result['type'] = 1;
            msg(0, '下单成功请支付', $result);
        } else {
            msg(1, $result["err_code_des"], $result);
        }
    }

    //导诊陪诊订单回调
    public function serverOrderBack()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $order_data = Db::name('server_order')
            ->where('order_no', '=', $order_no)
            ->find();
//        serverPaySuccess($order_data);
//        msg(0, "支付成功！", $order_data);
        $res = $app->order->queryByOutTradeNumber($order_no);
        if ($res['trade_state'] == "SUCCESS") {
            if ($order_data['status'] == 1) {
                serverPaySuccess($order_data);
            }
            $order_data = Db::name('server_order')
                ->where('order_no', '=', $order_no)
                ->find();
            msg(0, "支付成功！", $order_data);
        } else {
            msg(3, $res["err_code_des"] ? $res["err_code_des"] : $res['trade_state_desc'], '');
        }
    }

    //跨市订单
    //通过医院id获取开通省
    public function getRouteProvince()
    {
        $data = $this->request->param();
        $data_list = Db::name('route')
            ->where(['type' => 1, 'hospital_id' => $data['hospital_id'], 'is_del' => 0])
            ->order('sort desc')
            ->group('province')
            ->column('province');
        $return_data = array();
        foreach ($data_list as $k => $v) {
            $return_data[$k]['name'] = $v;
            $return_data[$k]['is_able'] = 1;
        }
        msg(0, '查询完成', $return_data);
    }

    //通过省获取开通市
    public function getRouteCityByProvince()
    {
        $data = $this->request->param();
        $data_list = Db::name('route')
            ->where(['type' => 1, 'hospital_id' => $data['hospital_id'], 'province' => $data['province'], 'is_del' => 0])
            ->order('sort desc')
            ->column('city');
        $return_data = array();
        foreach ($data_list as $k => $v) {
            $return_data[$k]['name'] = $v;
            $return_data[$k]['is_able'] = 1;
        }
        msg(0, '查询完成', $return_data);
    }

    //通过医院id获取市内开通地点
    public function getCityAddress()
    {
        $data = $this->request->param();
        $data_list = Db::name('route')
            ->where(['type' => 2, 'hospital_id' => $data['hospital_id'], 'is_del' => 0])
            ->order('sort desc')
            ->column('address');
        $return_data = array();
        foreach ($data_list as $k => $v) {
            $return_data[$k]['name'] = $v;
            $return_data[$k]['is_able'] = 1;
        }
        msg(0, '查询完成', $return_data);
    }

    //获取路线价格
    public function getRoutePrice()
    {
        $data = $this->request->param();
        $where[] = ['is_del', '=', 0];
        $where[] = ['hospital_id', '=', $data['hospital_id']];
        //1市外 0市内
        //1单程 2返程 3往返
        if ($data['type'] == 1) {
            $where[] = ['province', '=', $data['province']];
            $where[] = ['city', '=', $data['city']];
        } else {
            $where[] = ['address', '=', $data['address']];
        }
        $route_info = Db::name('route')->where($where)->find();
        if (!$route_info) {
            msg(-1, '路线未开通', '');
        }
        if ($data['route_type'] == 3) {
            $route_info['price'] = $route_info['d_price'];
        }
        msg(0, '查询完成', $route_info);
    }

    public function getRoutePrice2($hospital_id, $type, $province, $city, $address, $order_type)
    {
        //路线类型 1市外 2市内 route_type
        //1单程 2返程 3往返 order_type
        $where[] = ['is_del', '=', 0];
        $where[] = ['hospital_id', '=', $hospital_id];
        if ($type == 1) {
            $where[] = ['province', '=', $province];
            $where[] = ['city', '=', $city];
        } else {
            $where[] = ['address', '=', $address];
        }
        $route_info = Db::name('route')->where($where)->find();
        if (!$route_info) {
            return -1;
        }
        if ($order_type == 3) {
            return $route_info['d_price'];
        } else {
            return $route_info['price'];
        }
    }

    //创建接送订单
    public function createDriverOrder()
    {
        $data = $this->request->param();
        $data['go_time'] = substr_replace($data['go_time'], ' ', 5, 1);
        $go_time = strtotime(date('Y') . '-' . $data['go_time']);
        $insert_data = array(
            'order_no' => GetOrderSN(2),
            'hospital_id' => $data['hospital_id'],
            'create_time' => time(),
            'go_time' => $go_time,
            'order_type' => $data['order_type'],  //1单程 2返程 3往返
            'member_id' => $this->memberId,
            'people' => $data['people'],
            'phone' => $data['phone'],
            'people2' => $data['people2'],
            'phone2' => $data['phone2'],
            'age' => $data['age'],
            'sex' => $data['sex'],
            'relationship' => $data['relationship'],
            'past_medical_history' => $data['past_medical_history'],
            'remark' => $data['remark'],
            'history_of_allergies' => $data['history_of_allergies'],
            'route_type' => $data['route_type'],  //路线类型 1市外 2市内
            'address' => $data['address']
        );
        $hospital_info = Db::name('hospital')->find($data['hospital_id']);
        $insert_data['hospital_name'] = $hospital_info['name'];
        if ($data['route_type'] == 1) {
            $insert_data['province'] = $data['province'];
            $insert_data['city'] = $data['city'];
            $insert_data['area'] = $data['area'];
        } else {
            $insert_data['province'] = $hospital_info['province'];
            $insert_data['city'] = $hospital_info['province'];
            $insert_data['area'] = $hospital_info['area'];
        }
        Db::startTrans();
        try {
            $price = $this->getRoutePrice2(
                $data['hospital_id'],
                $data['route_type'],
                $data['province'],
                $data['city'],
                $data['address'],
                $data['order_type']
            );
            if ($price < 0) {
                msg(-2, '路线不存在', '');
            }
            $insert_data['price'] = $price;
            $insert_data['pay_money'] = $price;
            $vip_count = $this->getVipCount();
            if ($vip_count) {
                $vip_discount = number_format($insert_data['pay_money'] * ($vip_count / 100), 2);
                $insert_data['pay_money'] = $insert_data['pay_money'] - $vip_discount;
                $insert_data['vip_discount'] = $vip_discount;
            }
            //使用优惠卷
            if (isset($data['mc_id']) && $data['mc_id']) {
                $coupons_where = array(
                    'member_id' => $this->memberId,
                    'id' => $data['mc_id'],
                    'status' => 1,
                    'is_del' => 0,
                );
                $member_coupons = Db::name('member_coupons')
                    ->where($coupons_where)
                    ->find();
                if (!$member_coupons) {
                    msg(-1, '优惠券不存在', '');
                }
                if ($insert_data['pay_money'] < $member_coupons['min_amount']) {
                    msg(-1, '优惠券不可用', '');
                }
                $insert_data['mc_id'] = $data['mc_id'];
                $insert_data['coupon_money'] = $member_coupons['value'];
                $insert_data['pay_money'] = number_format($insert_data['pay_money'] - $member_coupons['value'], 2);
            }
            if (config('site.web_one_price')) {
                $insert_data['pay_money'] = 0.01;
            }
            $order_id = Db::name('driver_order')->insertGetId($insert_data);
            $insert_data['id'] = (int)$order_id;
            Db::commit();
            msg(0, '查询完成', $insert_data);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //接送订单微信发起支付
    public function payDriverOrder()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $type = $data['type'];   //1微信支付 2支付宝支付
        $order_data = Db::name('driver_order')
            ->where('order_no', '=', $order_no)
            ->find();
        if (!$order_data) {
            msg(-1, '订单有误', '');
        }
        $userInfo = $this->memberInfo;
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $jssdk = $app->jssdk;
        $pay_money = $order_data['pay_money'] * 100;
        if (config('site.web_one_price')) {
            $pay_money = 1;
        }
        $result = $app->order->unify([
            'body' => '交通服务',
            'out_trade_no' => $order_data['order_no'],
            'total_fee' => $pay_money,
            //           'total_fee' => 1,
//            'spbill_create_ip' => $orderdata['ip'], // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
//            'notify_url' => conf("lm", "url") . $config['notify_url'], // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $userInfo['openid'],
        ]);
        if ($result['return_code'] == "SUCCESS" && $result["result_code"] != "FAIL") {
            $config2 = $jssdk->bridgeConfig($result['prepay_id'], false);
            $result['msg'] = 'ok';
            $result['config'] = $config2;
            $result['order_no'] = $order_data['order_no'];
            $result['order_id'] = $order_data['id'];
            $result['type'] = 1;
            msg(0, '下单成功请支付', $result);
        } else {
            msg(1, $result["err_code_des"], $result);
        }
    }

    //接送订单回调
    public function driverOrderBack()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $order_data = Db::name('driver_order')
            ->where('order_no', '=', $order_no)
            ->find();
//        driverPaySuccess($order_data);
//        msg(0, "支付成功！", $order_data);
        $res = $app->order->queryByOutTradeNumber($order_no);
        if ($res['trade_state'] == "SUCCESS") {
            if ($order_data['status'] == 1) {
                driverPaySuccess($order_data);
            }
            $order_data = Db::name('driver_order')
                ->where('order_no', '=', $order_no)
                ->find();
            msg(0, "支付成功！", $order_data);
        } else {
            msg(3, $res["err_code_des"] ? $res["err_code_des"] : $res['trade_state_desc'], '');
        }
    }

    //获取会员陪诊 导诊订单列表
    public function getServerOrderList()
    {
        //0全部 1待支付2带指派3已指派4服务中5已完成
        // `status` 订单状态 1待支付2带指派3服务中4已完成5已取消6已退款7已指派8已评价',
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['is_del', '=', 0];
        $where[] = ['member_id', '=', $this->memberId];
//        if (isset($data['status']) && $data['status']) {
//            $where[] = ['status', '=', $data['status']];
//        }
        if ($data['status'] == 0) {
            $where[] = ['status', 'in', [1, 2, 3, 4, 7, 8]];
        }

        if ($data['status'] == 1) {
            $where[] = ['status', 'in', [1]];
        }

        if ($data['status'] == 2) {
            $where[] = ['status', 'in', [2]];
        }

        if ($data['status'] == 3) {
            $where[] = ['status', 'in', [7]];
        }
        if ($data['status'] == 4) {
            $where[] = ['status', 'in', [3]];
        }

        if ($data['status'] == 5) {
            $where[] = ['status', 'in', [4, 8]];
        }
        $data_count = Db::name('server_order')
            ->where($where)->count();
        $data_list = Db::name('server_order')
            ->where($where)
            ->order('create_time desc')
            ->page($page, $length)
            ->select();
        foreach ($data_list as $k => $v) {
            if ($v['status'] == 1) {
                $config = config('wechat.wxpay');
                $app = Factory::payment($config);
                $res = $app->order->queryByOutTradeNumber($v['order_no']);
                if ($res['trade_state'] == "SUCCESS") {
                    serverPaySuccess($v);
                }
            }
            $data_list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            if ($v['time']) {
                $data_list[$k]['time'] = date('Y-m-d H:i:s', $v['time']);
            }
            if ($v['pay_time']) {
                $data_list[$k]['pay_time'] = date('Y-m-d H:i:s', $v['pay_time']);
            }
            if ($v['dispatch_time']) {
                $data_list[$k]['dispatch_time'] = date('Y-m-d H:i:s', $v['dispatch_time']);
            }
            if ($v['start_time']) {
                $data_list[$k]['start_time'] = date('Y-m-d H:i:s', $v['start_time']);
            }
            if ($v['end_time']) {
                $data_list[$k]['end_time'] = date('Y-m-d H:i:s', $v['end_time']);
            }
            $hospital_info = Db::name('hospital')
                ->where('id', '=', $v['hospital_id'])
                ->find();
            if ($hospital_info) {
                $data_list[$k]['hospital_name'] = $hospital_info['name'];
            } else {
                $data_list[$k]['hospital_name'] = '';
            }

            //1陪诊订单 2导诊订单
            if ($v['order_type'] == 1) {
                $server_info = Db::name('server')->find($v['server_id']);
                $data_list[$k]['server_info'] = $server_info;
            } else {
                $server_info = Db::name('server2')->find();
                $data_list[$k]['server_info'] = $server_info;
            }
        }
        msg(0, '查询成功', $data_list, $data_count);
    }

    //陪诊导诊订单详情
    public function getServerOrderDetail()
    {
        $data = $this->request->param();
        $return_detail = Db::name('server_order')->find($data['id']);
        if (!$return_detail) {
            msg(-1, '订单不存在', '');
        }
        $return_detail['create_time'] = date('Y-m-d H:i:s', $return_detail['create_time']);
        if ($return_detail['time']) {
            $return_detail['time'] = date('Y-m-d H:i:s', $return_detail['time']);
        }
        if ($return_detail['pay_time']) {
            $return_detail['pay_time'] = date('Y-m-d H:i:s', $return_detail['pay_time']);
        }
        if ($return_detail['dispatch_time']) {
            $return_detail['dispatch_time'] = date('Y-m-d H:i:s', $return_detail['dispatch_time']);
        }
        if ($return_detail['start_time']) {
            $return_detail['start_time'] = date('Y-m-d H:i:s', $return_detail['start_time']);
        }
        if ($return_detail['end_time']) {
            $return_detail['end_time'] = date('Y-m-d H:i:s', $return_detail['end_time']);
        }
        $hospital_info = Db::name('hospital')->find($return_detail['hospital_id']);
        $return_detail['hospital_info'] = $hospital_info;
        $return_detail['pz_info'] = Db::name('pz')->find($return_detail['pz_id']);
        $return_detail['doctor_info'] = Db::name('doctor')->find($return_detail['doctor_id']);;
        //1陪诊订单 2导诊订单
        if ($return_detail['order_type'] == 1) {
            $server_info = Db::name('server')->find($return_detail['server_id']);
            $return_detail['server_info'] = $server_info;
        } else {
            $server_info = Db::name('server2')->find();
            $return_detail['server_info'] = $server_info;
            $return_detail['y_time1'] = date('Y-m-d H:i:s', $return_detail['y_time1']);
            $return_detail['y_time2'] = date('Y-m-d H:i:s', $return_detail['y_time2']);
            $return_detail['y_time3'] = date('Y-m-d H:i:s', $return_detail['y_time3']);
        }
        msg(0, '查询成功', $return_detail);
    }

    //完成陪诊导诊订单
    public function finishServerOrder()
    {
        $data = $this->request->param();
        $ServerOrderInfo = Db::name('server_order')->where([
            'id' => $data['id'],
            'is_del' => 0
        ])->find();
        if (!$ServerOrderInfo) {
            msg(-1, '订单不存在', '');
        }
        // todo 上线打开
//        if ($ServerOrderInfo['status'] != 3) {
//            msg(-2, '订单状态不正确', '');
//        }
        Db::startTrans();
        try {
            $update_data = array(
                'status' => 4,
                'id' => $data['id'],
                'end_time' => time()
            );
            //陪诊加钱
            $pz_info = Db::name('pz')->find($ServerOrderInfo['pz_id']);
            Db::name('pz')->where(['id' => $ServerOrderInfo['pz_id']])->setInc('order_num');
            addMoney($ServerOrderInfo,
                1,
                $pz_info['member_id'],
                $ServerOrderInfo['get_money'],
                '服务订单：' . $ServerOrderInfo['order_no'],
                1
            );
//            //分销加积分
            addFraction(
                $this->memberId,
                $ServerOrderInfo['pay_money'] * config('site.one_price_points'),
                '服务订单：' . $ServerOrderInfo['order_no'],
                3,
                1,
                '',
                '',
                $ServerOrderInfo['order_no'],
                1
            );
            //分销
            $this->addFxMoney($ServerOrderInfo, 1);
            Db::name('server_order')->update($update_data);
            Db::commit();
            msg(0, '修改成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //取消陪诊导诊订单
    public function cancelServerOrder()
    {
        $data = $this->request->param();
        $ServerOrderInfo = Db::name('server_order')->where([
            'id' => $data['id'],
            'is_del' => 0
        ])->find();
        if (!$ServerOrderInfo) {
            msg(-1, '订单不存在', '');
        }
        // todo 上线打开
//        if ($ServerOrderInfo['status'] != 1) {
//            msg(-2, '订单状态不是待支付', '');
//        }
        Db::startTrans();
        try {
            $update_data = array(
                'status' => 5,
                'id' => $data['id'],
                'cancel_time' => time()
            );
            Db::name('server_order')->update($update_data);
            Db::commit();
            msg(0, '修改成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //陪诊导诊订单退款
    public function refundServerOrder()
    {
        $data = $this->request->param();
        $order_id = $data['id'];//订单id
        $order_info = Db::name('server_order')->where('id', $order_id)->find();
        if (!$order_info) {
            msg(-1, '当前订单不存在', '');
        }
        //1待支付2带指派3服务中4已完成5已取消6已退款
        $array = [1, 3, 4, 5, 6];

        // todo 上线打开
//        if (in_array($order_info['status'], $array)) {
//            msg(-1, '当前订单不可退款', '');
//        }
        //支付方式 1微信支付 2套餐支付 3会员卡支付 4支付宝支付 5积分兑换卷支付
        Db::startTrans();
        try {
            $refundFee = 0;
            if ($order_info['time'] - time() < 7200) {
                tuikuanServerOrder($order_info);
                msg(0, '退款完成', $refundFee);
            }
            switch ($order_info['pay_type']) {
                case 1:
                    $config = config('wechat.wxpay');
                    $app = Factory::payment($config);
                    //todo 退款数额需要设置
                    if ($order_info['time'] - time() >= 86400) {
                        $refundFee = $order_info['pay_money'] * 100;
                    } else if ($order_info['time'] - time() < 86400 && $order_info['time'] - time() >= 7200) {
                        $refundFee = ceil($order_info['pay_money'] * 80);
                    }
                    if ($order_info['pay_money'] == 0.01) {
                        $refundFee = $order_info['pay_money'] * 100;
                    }
                    $result = $app->refund->byOutTradeNumber($order_info['order_no'], $order_info['order_no'], $order_info['pay_money'] * 100, $refundFee, [
                        // 可在此处传入其他参数，详细参数见微信支付文档
                        'refund_desc' => '陪诊导诊服务订单退款',
                    ]);
                    break;
                case 2:
                    Db::name('member_package_server')->where([
                        'id' => $order_info['exchange_id'],
                    ])->setInc('num');
                    break;
                case 3:
                    Db::name('member_mcard_server')->where([
                        'id' => $order_info['exchange_id'],
                    ])->setInc('num');
                    break;
                case 4:
                    self::appInit();
                    AlipayFactory::util()->generic()->execute(
                        'alipay.trade.refund',
                        [], [
                            'out_trade_no' => $order_info['order_no'], // 订单号
                            'refund_amount' => (string)$order_info['pay_money'], // 退款订单号
                        ]
                    );
                    //todo 退款数额需要设置
                    //todo 支付宝支付退款
                    break;
                case 5:
                    Db::name('member_server')->where([
                        'id' => $order_info['exchange_id'],
                    ])->setInc('num');
                    break;
                default:
            }
            tuikuanServerOrder($order_info, $refundFee);
            Db::commit();
            msg(0, '退款成功', $result);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //获取会员接送订单列表
    public function getDriverOrderList()
    {
        //0全部 1待支付2带指派3已指派4服务中5已完成
        // `status` 订单状态 1待支付2带指派3服务中4已完成5已取消6已退款7已指派8已评价',
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $where[] = ['is_del', '=', ''];
        $where[] = ['member_id', '=', $this->memberId];
//        if (isset($data['status']) && $data['status']) {
//            $where[] = ['status', '=', $data['status']];
//        }
        if ($data['status'] == 0) {
            $where[] = ['status', 'in', [1, 2, 3, 4, 7, 8]];
        }

        if ($data['status'] == 1) {
            $where[] = ['status', 'in', [1]];
        }

        if ($data['status'] == 2) {
            $where[] = ['status', 'in', [2]];
        }

        if ($data['status'] == 3) {
            $where[] = ['status', 'in', [7]];
        }

        if ($data['status'] == 4) {
            $where[] = ['status', 'in', [3]];
        }

        if ($data['status'] == 5) {
            $where[] = ['status', 'in', [4, 8]];
        }

        $data_list = Db::name('driver_order')
            ->where($where)
            ->order('create_time desc')
            ->page($page, $length)
            ->select();
        foreach ($data_list as $k => $v) {
            if ($v['status'] == 1) {
                $config = config('wechat.wxpay');
                $app = Factory::payment($config);
                $res = $app->order->queryByOutTradeNumber($v['order_no']);
                if ($res['trade_state'] == "SUCCESS") {
                    driverPaySuccess($v);
                }
            }
            $data_list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            if ($v['time']) {
                $data_list[$k]['time'] = date('Y-m-d H:i:s', $v['time']);
            }
            if ($v['pay_time']) {
                $data_list[$k]['pay_time'] = date('Y-m-d H:i:s', $v['pay_time']);
            }
            if ($v['dispatch_time']) {
                $data_list[$k]['dispatch_time'] = date('Y-m-d H:i:s', $v['dispatch_time']);
            }
            if ($v['start_time']) {
                $data_list[$k]['start_time'] = date('Y-m-d H:i:s', $v['start_time']);
            }
            if ($v['end_time']) {
                $data_list[$k]['end_time'] = date('Y-m-d H:i:s', $v['end_time']);
            }
            $hospital_info = Db::name('hospital')->find($v['hospital_id']);
            $data_list[$k]['hospital_name'] = $hospital_info['name'];
        }
        msg(0, '查询成功', $data_list);
    }

    //接送订单详情
    public function getDriverOrderDetail()
    {
        $data = $this->request->param();
        $return_detail = Db::name('driver_order')->find($data['id']);
        $return_detail['create_time'] = date('Y-m-d H:i:s', $return_detail['create_time']);
        if ($return_detail['go_time']) {
            $return_detail['go_time'] = date('Y-m-d H:i:s', $return_detail['go_time']);
        }
        if ($return_detail['start_time']) {
            $return_detail['start_time'] = date('Y-m-d H:i:s', $return_detail['start_time']);
        }
        if ($return_detail['end_time']) {
            $return_detail['end_time'] = date('Y-m-d H:i:s', $return_detail['end_time']);
        }
        if ($return_detail['pay_time']) {
            $return_detail['pay_time'] = date('Y-m-d H:i:s', $return_detail['pay_time']);
        }
        if ($return_detail['dispatch_time']) {
            $return_detail['dispatch_time'] = date('Y-m-d H:i:s', $return_detail['dispatch_time']);
        }
        //tui_time
        if ($return_detail['tui_time']) {
            $return_detail['tui_time'] = date('Y-m-d H:i:s', $return_detail['tui_time']);
        }
        $server_info = Db::name('server3')->find();
        $return_detail['server_info'] = $server_info;
        $return_detail['driver_info'] = Db::name('driver')->find($return_detail['driver_id']);;
        msg(0, '查询成功', $return_detail);
    }
    //接送订单完成
    //1待支付2带指派3服务中4已完成5已取消6已退款7已派遣
    public function finishDriverOrder()
    {
        $data = $this->request->param();
        $ServerOrderInfo = Db::name('driver_order')->where([
            'id' => $data['id'],
        ])->find();
        if (!$ServerOrderInfo) {
            msg(-1, '订单不存在', '');
        }
        //todo 上线放开
//        if ($ServerOrderInfo['status'] != 3) {
//            msg(-2, '订单状态不正确', '');
//        }
        Db::startTrans();
        try {
            $update_data = array(
                'status' => 4,
                'id' => $data['id'],
                'end_time' => time()
            );
            $driver_info = Db::name('driver')->find($ServerOrderInfo['driver_id']);
            addMoney($ServerOrderInfo,
                2,
                $driver_info['member_id'],
                $ServerOrderInfo['get_money'],
                '接送订单：' . $ServerOrderInfo['order_no'],
                1
            );
            addFraction(
                $this->memberId,
                $ServerOrderInfo['pay_money'] * config('site.one_price_points'),
                '接送订单：' . $ServerOrderInfo['order_no'],
                3,
                1,
                '',
                '',
                $ServerOrderInfo['order_no'],
                2
            );
            $this->addFxMoney($ServerOrderInfo, 2);
            Db::name('driver_order')->update($update_data);
            Db::commit();
            msg(0, '修改成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //接送订单取消
    public function cancelDriverOrder()
    {
        $data = $this->request->param();
        $ServerOrderInfo = Db::name('driver_order')->where([
            'id' => $data['id'],
            'is_del' => 0
        ])->find();

        if (!$ServerOrderInfo) {
            msg(-1, '订单不存在', '');
        }
        //todo 上线放开
//        if ($ServerOrderInfo['status'] != 1) {
//            msg(-2, '订单状态不是待支付', '');
//        }
        Db::startTrans();
        try {
            $update_data = array(
                'status' => 5,
                'id' => $data['id'],
                'cancel_time' => time()
            );
            Db::name('driver_order')->update($update_data);
            Db::commit();
            msg(0, '修改成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //接送订单退款
    public function refundDriverOrder()
    {
        $data = $this->request->param();
        $order_id = $data['id'];//订单id
        $order_info = Db::name('driver_order')->where('id', $order_id)->find();
        if (!$order_info) {
            msg(-1, '当前订单不存在', '');
        }
        //1待支付2带指派3服务中4已完成5已取消6已退款7已派遣8已评价
        //1待支付2带指派3服务中4已完成5已取消6已退款
        $array = [1, 4, 5, 6, 8];
        if (in_array($order_info['status'], $array)) {
            msg(-1, '当前订单不可退款', '');
        }
        if ($order_info['server_order_id']) {
            $server_order_info = Db::name('server_order')->find($order_info['server_order_id']);
            $order_info['order_no'] = $server_order_info['order_no'];
        }
        Db::startTrans();
        try {
            if ($order_info['pay_type']==1){
                $config = config('wechat.wxpay');
                $app = Factory::payment($config);
                $result = $app->refund->byOutTradeNumber($order_info['order_no'], $order_info['order_no'], $order_info['pay_money'] * 100, $order_info['pay_money'] * 100, [
                    // 可在此处传入其他参数，详细参数见微信支付文档
                    'refund_desc' => '订单退款',
                ]);
            }else{
                self::appInit();
                AlipayFactory::util()->generic()->execute(
                    'alipay.trade.refund',
                    [], [
                        'out_trade_no' => $order_info['order_no'], // 订单号
                        'refund_amount' => (string)$order_info['pay_money'], // 退款订单号
                    ]
                );
            }
            //写退款
            tuikuanDriverOrder($order_info, $order_info['pay_money']);
            Db::commit();
            msg(0, '修改成功', $result);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //创建评价 type 1陪诊 2导诊 3接送服务
    public function createComment()
    {
        $data = $this->request->param();
        $type = $data['type'];
        $insert_data = array(
            'member_id' => $this->memberId,
            'type' => $type,
            'order_id' => $data['order_id'],
            'content' => $data['content'],
            'score' => $data['score'],
            'anonymous' => $data['anonymous'] ? $data['anonymous'] : 0,
            'create_time' => time(),
        );
        if ($data['label'] && isset($data['label'])) {
            $insert_data['label'] = implode(',', $data['label']);
        }
        Db::startTrans();
        try {
            if ($type == 1 || $type == 2) {
                $order_info = Db::name('server_order')
                    ->where([
                        'id' => $data['order_id'],
                        'member_id' => $this->memberId,
                    ])->find();
                $insert_data['pz_id'] = $order_info['pz_id'];
                $insert_data['hospital_id'] = $order_info['hospital_id'];
                $insert_data['server_id'] = $order_info['server_id'];
                Db::name('server_order')->update([
                    'id' => $data['order_id'],
                    'status' => 8
                ]);
            } else {
                $order_info = Db::name('driver_order')
                    ->where([
                        'id' => $data['order_id'],
                        'member_id' => $this->memberId,
                    ])->find();
                $insert_data['driver_id'] = $order_info['driver_id'];
                Db::name('driver_order')->update([
                    'id' => $data['order_id'],
                    'status' => 8
                ]);
            }
            $insert_data['order_no'] = $order_info['order_no'];
            if (!$order_info) {
                msg(-1, '订单不存在', '');
            }
            //todo 开启放开
//        if ($order_info['status'] != 4) {
//            msg(-1, '订单不可评价', '');
//        }
            $comment_id = Db::name('comment')->insertGetId($insert_data);
            if (isset($data['comment_imgs']) && $data['comment_imgs']) {
                foreach ($data['comment_imgs'] as $k => $v) {
                    Db::name('comment_img')->insertGetId(
                        [
                            'comment_id' => $comment_id,
                            'img_url' => $v,
                            'sort' => $k + 1
                        ]
                    );
                }
            }
            Db::commit();
            msg(0, '查询成功', $comment_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //获取陪诊导诊评价顶部
    public function getPzCommentTop()
    {
        $data = $this->request->param();
        $order_count = Db::name('comment')
            ->where([
                'server_id' => $data['server_id'],
                'status' => 1,
                'is_del' => 0,
            ])
            ->where('type', 'in', [1, 2])
            ->count();
        $order_score = Db::name('comment')
            ->where([
                'server_id' => $data['server_id'],
                'status' => 1,
                'is_del' => 0,
            ])
            ->where('type', 'in', [1, 2])
            ->sum('score');
        if ($order_score == 0) {
            $score = 0;
        } else {
            $score = number_format($order_score / $order_count, 1);
        }
        $return_data['count'] = $order_count;
        $return_data['score'] = $score;
        $comment = Db::name('comment')->where([
                'server_id' => $data['server_id'],
                'is_del' => 0,
                'status' => 1,
            ]
        )->where('label', '<>', null)->column('label');
        $comment_labs = array();
        foreach ($comment as $k => $v) {
            $comment2 = explode(',', $v);
            foreach ($comment2 as $k2 => $v2) {
                $comment_labs[] = $v2;
            }
        }
        $comment_labs = array_unique($comment_labs);
//        $comment_labs = array_count_values($comment_labs);
        $return_data['comment_labs'] = $comment_labs;
        msg(0, '查询成功', $return_data);
    }

    //陪诊导诊评价列表
    public function getCommentList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 100);
        $comment_list = Db::name('comment')
            ->where([
                'server_id' => $data['server_id'],
                'status' => 1,
                'is_del' => 0,
            ])->order('create_time desc')
            ->paginate(
                $length, false, [
                    'page' => $page
                ]
            )->each(function ($item) {
                //判断是否匿名用户
//                if ($item['anonymous']) {
//                    $item['user_name'] = '匿名用户';
//                    $item['user_avatar_url'] = config('site.web_default_avatar');
//                } else {
//                    $member_info = Db::name('member')->find($item['member_id']);
//                    $item['user_name'] = $member_info['nickname'];
//                    $item['user_avatar_url'] = $member_info['avatarUrl'];
//                }
                $member_info = Db::name('member')->find($item['member_id']);
                $item['user_name'] = $member_info['nickname'];
                $item['user_avatar_url'] = $member_info['avatarUrl'];
                $item['label'] = explode(',', $item['label']);
                //评价图片
                $item['img'] = Db::name('comment_img')
                    ->where('comment_id', '=', $item['id'])
                    ->order('sort desc')
                    ->column('img_url');
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                return $item;
            });
        msg(0, '查询成功', $comment_list);
    }

    //获取接送评价顶部
    public function getPzCommentTop2()
    {
        $data = $this->request->param();
        $order_count = Db::name('comment')
            ->where([
                'status' => 1,
                'type' => 3,
                'is_del' => 0,
            ])->count();
        $order_score = Db::name('comment')
            ->where([
                'status' => 1,
                'type' => 3,
                'is_del' => 0,
            ])->count('score');
        if ($order_score == 0) {
            $score = 0;
        } else {
            $score = number_format($order_score / $order_count, 1);
        }
        $return_data['count'] = $order_count;
        $return_data['score'] = $score;
        $comment = Db::name('comment')->where([
                'status' => 1,
                'type' => 3,
                'is_del' => 0,
            ]
        )->where('label', '<>', null)->column('label');
        $comment_labs = array();
        foreach ($comment as $k => $v) {
            $comment2 = explode(',', $v);
            foreach ($comment2 as $k2 => $v2) {
                $comment_labs[] = $v2;
            }
        }
        $comment_labs = array_unique($comment_labs);
//        $comment_labs = array_count_values($comment_labs);
        $return_data['comment_labs'] = $comment_labs;
        msg(0, '查询成功', $return_data);
    }

    //陪诊接送评价列表
    public function getCommentList2()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 100);
        $comment_list = Db::name('comment')
            ->where([
                'status' => 1,
                'type' => 3,
                'is_del' => 0,
            ])->order('create_time desc')
            ->paginate(
                $length, false, [
                    'page' => $page
                ]
            )->each(function ($item) {
                $member_info = Db::name('member')->find($item['member_id']);
                $item['user_name'] = $member_info['nickname'];
                $item['user_avatar_url'] = $member_info['avatarUrl'];
                $item['label'] = explode(',', $item['label']);
                //评价图片
                $item['img'] = Db::name('comment_img')
                    ->where('comment_id', '=', $item['id'])
                    ->order('sort desc')
                    ->column('img_url');
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                return $item;
            });
        msg(0, '查询成功', $comment_list);
    }


    //创建购买套餐
    public function createPackageOrder()
    {
        $data = $this->request->param();
        $package_info = Db::name('package')->find($data['package_id']);
        $insert_data = array(
            'order_no' => GetOrderSN(2),
            'member_id' => $this->memberId,
            'package_id' => $data['package_id'],
            'create_time' => time(),
            'price' => $package_info['price'],
            'pay_money' => $package_info['price']
        );
        if (config('site.web_one_price')) {
            $insert_data['pay_money'] = 0.01;
        }
        Db::startTrans();
        try {
            session_start();
            $lsterRequestTime = $_SESSION[$this->memberId . 'last_time2'] ?? 0;
            $currenTRequestTime = time();
            $debounce = 5;
            if ($currenTRequestTime - $lsterRequestTime < $debounce) {
                msg(-1, '下单过频繁，请稍后下单', '');
            } else {
                $_SESSION[$this->memberId . 'last_time2'] = $currenTRequestTime;
            }
            $order_id = Db::name('package_order')->insertGetId($insert_data);
            $order_info = Db::name('package_order')->find($order_id);
            Db::commit();
            msg(0, '创建完成', $order_info);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //发起套餐微信支付
    public function payPackageOrder()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $order_data = Db::name('package_order')
            ->where('order_no', '=', $order_no)
            ->find();
        if (!$order_data) {
            msg(-1, '订单有误', '');
        }
        $userInfo = $this->memberInfo;
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $jssdk = $app->jssdk;
        $pay_money = $order_data['pay_money'] * 100;
        if (config('site.web_one_price')) {
            $pay_money = 1;
        }
        $result = $app->order->unify([
            'body' => '套餐购买',
            'out_trade_no' => $order_data['order_no'],
            'total_fee' => $pay_money,
            //           'total_fee' => 1,
//            'spbill_create_ip' => $orderdata['ip'], // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
//            'notify_url' => conf("lm", "url") . $config['notify_url'], // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $userInfo['openid'],
        ]);
        if ($result['return_code'] == "SUCCESS" && $result["result_code"] != "FAIL") {
            $config2 = $jssdk->bridgeConfig($result['prepay_id'], false);
            $result['msg'] = 'ok';
            $result['config'] = $config2;
            $result['order_no'] = $order_data['order_no'];
            $result['order_id'] = $order_data['id'];
            $result['type'] = 1;
            msg(0, '下单成功请支付', $result);
        } else {
            msg(1, $result["err_code_des"], $result);
        }
    }

    //购买套餐回调
    public function packageOrderBack()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $order_data = Db::name('package_order')
            ->where('order_no', '=', $order_no)
            ->find();

        $res = $app->order->queryByOutTradeNumber($order_no);
        if ($res['trade_state'] == "SUCCESS") {
            if ($order_data['status'] == 1) {
                //给用户发送套餐
                $mp_id = giveMemberPackage2($order_data['package_id'], $this->memberId);
                //更新订单状态
                $update_package_order = array(
                    'id' => $order_data['id'],
                    'status' => 2,
                    'pay_time' => time(),
                    'fx_money' => getFxMoney($order_data, 3),
                    'mp_id' => $mp_id
                );
                Db::name('package_order')->update($update_package_order);
                //发送积分
                addFraction(
                    $this->memberId,
                    $order_data['pay_money'] * config('site.one_price_points'),
                    '套餐订单：' . $order_data['order_no'],
                    3,
                    1,
                    '',
                    '',
                    $order_data['order_no'],
                    3
                );
                $this->addFxMoney($order_data, 3);
            }
            msg(0, "支付成功！", $order_data);
        } else {
            msg(3, $res["err_code_des"] ? $res["err_code_des"] : $res['trade_state_desc'], '');
        }
    }

    //创建会员卡购买订单
    public function createVipOrder()
    {
        $data = $this->request->param();
        $mcard_info = Db::name('mcard')->find($data['mcard_id']);
        $insert_data = array(
            'order_no' => GetOrderSN(2),
            'member_id' => $this->memberId,
            'mcard_id' => $data['mcard_id'],
            'create_time' => time(),
            'price' => $mcard_info['price'],
            'pay_money' => $mcard_info['price'],
            'status' => 1
        );
        if (config('site.web_one_price')) {
            $insert_data['pay_money'] = 0.01;
        }
        Db::startTrans();
        try {
            session_start();
            $lsterRequestTime = $_SESSION[$this->memberId . 'last_time4'] ?? 0;
            $currenTRequestTime = time();
            $debounce = 5;
            if ($currenTRequestTime - $lsterRequestTime < $debounce) {
                msg(-1, '下单过频繁，请稍后下单', '');
            } else {
                $_SESSION[$this->memberId . 'last_time4'] = $currenTRequestTime;
            }
            $order_id = Db::name('mcard_order')->insertGetId($insert_data);
            $order_info = Db::name('mcard_order')->find($order_id);
            Db::commit();
            msg(0, '创建完成', $order_info);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //发起会员卡微信支付
    public function payVipOrder()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $order_data = Db::name('mcard_order')
            ->where('order_no', '=', $order_no)
            ->find();
        if (!$order_data) {
            msg(-1, '订单有误', '');
        }
        $userInfo = $this->memberInfo;
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $jssdk = $app->jssdk;
        $pay_money = $order_data['pay_money'] * 100;
        if (config('site.web_one_price')) {
            $pay_money = 1;
        }
        $result = $app->order->unify([
            'body' => '会员卡购买',
            'out_trade_no' => $order_data['order_no'],
            'total_fee' => $pay_money,
            //           'total_fee' => 1,
//            'spbill_create_ip' => $orderdata['ip'], // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
//            'notify_url' => conf("lm", "url") . $config['notify_url'], // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $userInfo['openid'],
        ]);
        if ($result['return_code'] == "SUCCESS" && $result["result_code"] != "FAIL") {
            $config2 = $jssdk->bridgeConfig($result['prepay_id'], false);
            $result['msg'] = 'ok';
            $result['config'] = $config2;
            $result['order_no'] = $order_data['order_no'];
            $result['order_id'] = $order_data['id'];
            $result['type'] = 1;
            msg(0, '下单成功请支付', $result);
        } else {
            msg(1, $result["err_code_des"], $result);
        }
    }

    //购买会员卡回调
    public function packageVipOrder()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $order_data = Db::name('mcard_order')
            ->where('order_no', '=', $order_no)
            ->find();
        $res = $app->order->queryByOutTradeNumber($order_no);
        if ($res['trade_state'] == "SUCCESS") {
            if ($order_data['status'] == 1) {
                $mcard_list_id = vip($order_data['mcard_id'], $this->memberId);
                //更新订单状态
                $update_mcard_order = array(
                    'id' => $order_data['id'],
                    'status' => 2,
                    'pay_time' => time(),
                    'mcard_list_id' => $mcard_list_id,
                    'fx_money' => getFxMoney($order_data, 4)
                );
                Db::name('mcard_order')->update($update_mcard_order);
                addFraction(
                    $this->memberId,
                    $order_data['pay_money'] * config('site.one_price_points'),
                    '会员卡订单：' . $order_data['order_no'],
                    3,
                    1,
                    '',
                    '',
                    $order_data['order_no'],
                    4
                );
                $this->addFxMoney($order_data, 4);
            }
            msg(0, "支付成功！", $order_data);
        } else {
            msg(3, $res["err_code_des"] ? $res["err_code_des"] : $res['trade_state_desc'], '');
        }
    }

    public function getMyServer()
    {
        $data_list = Db::name('member_server')->where([
            ['num', '>', 0],
            ['member_id', '=', $this->memberId],
            ['is_del', '=', 0]
        ])->order('create_time desc')->select();
        foreach ($data_list as $k => $v) {
            $server_info = Db::name('server')->find($v['server_id']);
            $server_info['tag'] = explode(',', $server_info['tag']);
            $data_list[$k]['server_info'] = $server_info;
        }
        msg(0, '查询成功', $data_list);
    }

    public function getRole()
    {
        $return['is_pz'] = 0;
        $return['is_driver'] = 0;
        $pz_info = Db::name('pz')->where([
            'member_id' => $this->memberId,
            'is_del' => 0,
            'status' => 1
        ])->find();
        $driver_info = Db::name('driver')->where([
            'member_id' => $this->memberId,
            'is_del' => 0,
            'status' => 1])->find();
        if ($pz_info) {
            $return['is_pz'] = 1;
        }
        if ($driver_info) {
            $return['is_driver'] = 1;
        }
        msg(0, '查询成功', $return);
    }

    //增加分销收入 type 1陪诊订单 2接送订单 3购买套餐返现 4购买会员卡返现
    public function addFxMoney($order_info, $type = 1)
    {
        //判断你的邀请用户是不是分销人员 invite_id
        $fx_info = Db::name('fx')
            ->where(['member_id' => $this->memberInfo['invite_id'], 'status' => 1, 'is_del' => 0])
            ->find();
        if (!$fx_info) {
            return 0;
        }
        $money = 0;
        $desc = '';
        //返现用户实际支付的钱
        switch ($type) {
            case 1:
                // 当expression等于value1时执行的代码
                $money = number_format($order_info['pay_money'] * ($fx_info['rate'] / 100), 2);
                $desc = '陪诊订单' . $order_info['order_no'];
                break;
            case 2:
                // 当expression等于value2时执行的代码
                $money = number_format($order_info['pay_money'] * ($fx_info['rate2'] / 100), 2);
                $desc = '接送订单' . $order_info['order_no'];
                break;
            case 3:
                $money = number_format($order_info['pay_money'] * ($fx_info['rate3'] / 100), 2);
                $desc = '购买套餐' . $order_info['order_no'];
                break;
            case 4:
                $money = number_format($order_info['pay_money'] * ($fx_info['rate4'] / 100), 2);
                $desc = '购买会员卡' . $order_info['order_no'];
                break;
        }
        if ($money) {
            addMoney($order_info, 3, $this->memberInfo['invite_id'], $money, $desc, 1, $type, $this->memberId);
        }
    }

    //订单支付发起测试
    public function payGoodsOrder()
    {
        //库存为0不能下订单
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $order_data = Db::name('driver_order')
            ->where('order_no', '=', $order_no)
            ->find();
        if (!$order_data) {
            msg(-1, '订单有误', '');
        }
        $userInfo = $this->memberInfo;
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $jssdk = $app->jssdk;
        $pay_money = $order_data['pay_money'] * 100;
        if (config('site.web_one_price')) {
            $pay_money = 1;
        }
        $result = $app->order->unify([
            'body' => '交通服务',
            'out_trade_no' => $order_data['order_no'],
            'total_fee' => $pay_money,
            //           'total_fee' => 1,
//            'spbill_create_ip' => $orderdata['ip'], // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
//            'notify_url' => conf("lm", "url") . $config['notify_url'], // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $userInfo['openid'],
        ]);
        if ($result['return_code'] == "SUCCESS" && $result["result_code"] != "FAIL") {
            $config2 = $jssdk->bridgeConfig($result['prepay_id'], false);
            $result['msg'] = 'ok';
            $result['config'] = $config2;
            $result['order_no'] = $order_data['order_no'];
            $result['order_id'] = $order_data['id'];
            $result['type'] = 1;
            msg(0, '下单成功请支付', $result);
        } else {
            msg(1, $result["err_code_des"], $result);
        }
    }

//   <--------------------------- 地址相关 ------------------------------->
    //增加收货地址
    public function addAddress()
    {
        $data = $this->request->param();
        $save_data = array(
            'member_id' => $this->memberInfo['id'],
            'realname' => $data['realname'],
            'telphone' => $data['telphone'],
            'province' => $data['province'],
            'city' => $data['city'],
            'area' => $data['area'],
            'address' => $data['address'],
            'is_default_address' => $data['is_default_address'],
            'create_time' => time()
        );

        Db::startTrans();
        try {
            if ($data['is_default_address']) {
                Db::name('address')
                    ->where(['member_id' => $this->memberInfo['id']])
                    ->update(['is_default_address' => 0]);
            }
            $insert_id = Db::name('address')->insertGetId($save_data);
            Db::commit();
            msg(0, '添加成功', $insert_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //编辑收货地址
    public function editAddress()
    {
        $data = $this->request->param();
        $save_data = array(
            'realname' => $data['realname'],
            'telphone' => $data['telphone'],
            'province' => $data['province'],
            'city' => $data['city'],
            'area' => $data['area'],
            'address' => $data['address'],
            'is_default_address' => $data['is_default_address'],
        );
        Db::startTrans();
        try {
            if ($data['is_default_address']) {
                Db::name('address')
                    ->where(['member_id' => $this->memberInfo['id']])
                    ->update(['is_default_address' => 0]);
            }
            $num = Db::name('address')
                ->where(['id' => $data['id']])
                ->update($save_data);
            Db::commit();
            msg(0, '编辑成功', $num);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //删除地址
    public function delAddress()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            $num = Db::name('address')
                ->where(['id' => $data['id']])
                ->update(['is_del' => 1]);
            Db::commit();
            msg(0, '编辑成功', $num);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //设置为默认地址
    public function setDefaultAddress()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            Db::name('address')
                ->where(['member_id' => $this->memberInfo['id']])
                ->update(['is_default_address' => 0]);
            Db::name('address')
                ->where(['id' => $data['id'], 'member_id' => $this->memberInfo['id']])
                ->update(['is_default_address' => 1]);
            Db::commit();
            msg(0, '编辑成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    /**
     * 获取默认地址
     * @return array|\PDOStatement|string|\think\Model|void|null
     */
    public function getDefaultAddress()
    {
        $data = $this->getAddress();
        msg(0, '查询成功', $data);
    }

    /**
     * 通过id获取地址
     * @return array|\PDOStatement|string|\think\Model|void|null
     */
    public function getAddress2()
    {
        $data = $this->request->param();
        $addressData = $this->getAddressById($data['id']);
        msg(0, '查询成功', $addressData);
    }

    //获取地址列表
    public function getAddressList()
    {
        $member_id = $this->memberInfo['id'];
        $where[] = ['is_del', '=', 0];
        $where[] = ['member_id', '=', $member_id];
        $data = Db::name('address')
            ->where($where)
            ->order('is_default_address desc')
            ->order('create_time desc')
            ->select();
        foreach ($data as $k => $v) {
            $data[$k]['right'] = 0;
        }
        msg(0, "查询成功", $data);
    }

    public function getAddress()
    {
        $where[] = ['is_default_address', '=', 1];
        $where[] = ['is_del', '=', 0];
        $where[] = ['member_id', '=', $this->memberInfo['id']];
        $data = Db::name('address')->where($where)->find();
        return $data;
    }


    public function getAddressById($id)
    {
        return Db::name('address')->find($id);
    }

    public function tuikuanApi()
    {
        $data = $this->request->param();
        //type 1陪诊导诊 2接送 3套餐 4会员卡
        switch ($data['type']) {
            case 1:
                $order_info = Db::name('server_order')->where([
                    'order_no' => $data['order_no']
                ])->find();
                break;
            case 2:
                $order_info = Db::name('driver_order')->where([
                    'order_no' => $data['order_no']
                ])->find();
                break;
            case 3:
                $order_info = Db::name('package_order')->where([
                    'order_no' => $data['order_no']
                ])->find();
                break;
            case 4:
                $order_info = Db::name('mcard_order')->where([
                    'order_no' => $data['order_no']
                ])->find();
                break;
            default:
                $order_info = Db::name('server_order')->where([
                    'order_no' => $data['order_no']
                ])->find();
        }
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $result = $app->refund->byOutTradeNumber($order_info['order_no'],
            $order_info['order_no'],
            $order_info['pay_money'] * 100,
            $order_info['pay_money'] * 100,
            [
                // 可在此处传入其他参数，详细参数见微信支付文档
                'refund_desc' => '订单退款',
            ]);
        msg(0, '修改成功', $result);
    }


    //支付宝初始化
    public static function appInit($type = 0)
    {

        $data = [
            'appid' => '2021005100634222',
            'encryptKey' => 'ruwU8hf2SvNwSfgLNjZo4w==',
            'gateway' => 'https://openapi.alipay.com/gateway.do',
            'private_key' => 'MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCwvk+U0e98BoS0y659n+PXuDsLvDv6h/YLI3HmEhbHMH692ZgbdFvOoc7y4kONjiZrBqAAnmnwY9Sv9I0r7L26/DpJyd8ESZmQ7QaDgCWXIEd1cXxuF0bYpsbei/FXKp2tedW+R0HJcLvaH+/l+uVQJGFxvngyq5C5GC4Ft5vgJeouNRpDxw7SQNh2FZmdQPaZcPS9uz76YPQIsZWp9kssy3NQKMHcEoWPfWLIP9QU7046jrPx87EDynx/v7XCHxPUXc82FMDhulSbDX+93A0vMOg1Zecc33g/RS6OYMbbWWzOJJtCs8UK9jtgPjpYcdkU6K5gkZ0OgCjarXE3D0hTAgMBAAECggEAevRqOIWzrPx75aqswQgyYSfxK8DPmQJs0GLgIcYDwp6iDUEK6E6Sb7VxWta9WATEBUCens+Vs34/wAjJDP2tIB/IDP07AKiTBJdgKKtFe1UhYTqJ7ayTxLSBNOD2DEXBW6WeZLj9sz2R8bS2F6/rR02H3LE8vUNNcva3TZLmBZAywSXGv5yuGZi5fpO8I7s2+GjqPRmz1WMp4z66D6q2Bw0WMb5F2RanWEtgtHd5wx9hAdFNeflrN8xxNY/okz6f8BdzqXuALwvsRvRzjCtS0Nb8qSvBv9yC2DZNTvqdl9yE1NlPGkYWhwCSGIPSmG1FzaVvPs78308j9giuSKz0AQKBgQDag/edyVUKI2psv9PHgyZVjoXpqXXVTKeQT69nIwCRfilZDTr5A2/0FGBY2n6OzmwKlwZT2BndxYysXGkxZw3GBx4/cOathmLbCcEU4jAKC4b1TjbQ/LGGzgJPKcZ6tg6JaudlPRyvW/B1Gxv94FPYbDVO+2ZlHzYJn4FsTiYHEwKBgQDPD++64xcRXDDq4oTfCr61DoMsSUy6w72duTrL2LuREH8rj/EcZry1mkXSGAYZJjVwdl//Apaj73QSKM/bWS947qwc0HWrQzJOpxSoTi4EVCriPJ6m1pCplqxb7UuSV4vcgdcV1sEUnzc5tXIht8USElWvx0jM2siNy6dvf2uhwQKBgHOni2SBDjh6fDao5S9g8+YutCPzJEHL+5g/BMhi10cqbjoK7Z6kuhmGu2Pr6TYufTKxspCn/TDLAWSs2KRkNf8M/252lDFdwm7KX95sxR5b8YdeaVb9l/yQhtpdcwa520HSSjzkNo197OweeBdMJzSSOTjfiNeWyGQZf0fSqP/vAoGAUHCsfToDmCbsihN98vhFpikBJI9FU7j/TOrMwKxuEakK/m1pCdOPtC0+uqPCmrqRQCN8n6DtzLoVqYhZV6mKG7z8+CSz0djFDnEyQUA9+EiKcGGEcOQiRv/V7dB971g7aWq3mDBZyh0gYzbuI9M0qBSfXS5aRdso1o0retFRiwECgYAy3YRChjF4DbWoV7+O56fnA+TE2z3J2Ef6dwgs6ppJ/pqIyPgNvsWdKSuM8W5BaytMcuFbA76hg3vWoJm8AXQ5tCk7kzl7I6UevMoaBX1emn8Yi9pAmbG5yXYAgr4/u8Plq/cpgl5T6j562q6IR0mmfCjQiKGJetLIfyrw8YXQZw==',
            'alipay_public_key' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA7pXctJBsRPPCKAZXEIs9wawj4c2nSRDwDVMwjgGjhi5guRq90KdT8MxWUOpn3EilIQohKvl7f7odK+t7ElClZbPRhGtO0+GwOq8Dz6TngtqMa7OOkoRZLdJ2Cqr+mw06Ia2VkrNwzJ52eJPKC45WsDnJnvTRU8DcyNOdvIuJ2R5uoEQVM/wvq03yDLukIsgagC43FMMFA6EhKsthsaVQPAEDyOjKDZj0nlCnqPhTPR+OShNQq7+OUz/R/b1lDUoLhfqm95F6QgkEkOx99GZB2LKbDXBf0tE1IROX+Nqqq45dozNOSXFHth/q21e+22/0beTqlImRFHxtomrzF+4J2QIDAQAB'
        ];
        $config = new Config();
        $config->protocol = 'https';
        $config->gatewayHost = 'openapi.alipay.com';
        $config->signType = 'RSA2';
//        $config->signType = 'AES';
        $config->appId = $data['appid'];
        $config->merchantPrivateKey = $data['private_key'];
        $config->alipayPublicKey = $data['alipay_public_key'];
        $config->encryptKey = $data['encryptKey'];

        AlipayFactory::setOptions($config);
//        return Factory::base();
    }

    //支付宝发起支付
    public function repayAliyap()
    {
        self::appInit();
        $result = AlipayFactory::util()->generic()
            ->asyncNotify("")
            ->execute(
                'alipay.trade.create',
                [], [
                    'out_trade_no' => GetOrderSN(2),
                    'total_amount' => '88.88',
                    'subject' => 'Iphone6 16G',
                    'product_code' => 'JSAPI_PAY',
                    'op_app_id' => '2021005100634222',
                    'buyer_open_id' => '0651Bp9d8S3AN390gSvm65qSHw24Mcv9HpJF9dWayBYgc0f',
                    'op_buyer_open_id' => '0651Bp9d8S3AN390gSvm65qSHw24Mcv9HpJF9dWayBYgc0f'
                ]
            );
        msg(0, '下单成功请支付', json_decode($result->httpBody, true));
        dump($result->httpBody);
        die;
        return json_decode($result->httpBody);
    }
    //todo 发起支付
    //导诊陪诊订单支付宝发起支付
    public function payServerOrderAli()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $order_data = Db::name('server_order')
            ->where('order_no', '=', $order_no)
            ->find();
        if (!$order_data) {
            msg(-1, '订单有误', '');
        }
        $pay_money = $order_data['pay_money'] * 100;
        if ($order_data['is_car'] == 1) {
            $driver_order = Db::name('driver_order')->where([
                'server_order_id' => $order_data['id']
            ])->find();
            if ($driver_order) {
                $pay_money = ($order_data['pay_money'] + $driver_order['pay_money']) * 100;
            }
        }
        if (config('site.web_one_price')) {
            $pay_money = 1;
        }
        self::appInit();
        $result = AlipayFactory::util()->generic()
            ->asyncNotify(config('wechat.url').'/payServerOrderAliBack')
            ->execute(
                'alipay.trade.create',
                [], [
                    'out_trade_no' =>$order_no,
                    'total_amount' => round($pay_money / 100, 2),
                    'subject' => '陪诊服务',
                    'product_code' => 'JSAPI_PAY',
                    'op_app_id' => '2021005100634222',
                    'buyer_open_id' => $this->memberInfo['zfb_open_id'],
                    'op_buyer_open_id' => $this->memberInfo['zfb_open_id']
//                    'buyer_open_id' => '0651Bp9d8S3AN390gSvm65qSHw24Mcv9HpJF9dWayBYgc0f',
//                    'op_buyer_open_id' => '0651Bp9d8S3AN390gSvm65qSHw24Mcv9HpJF9dWayBYgc0f'
                ]
            );
        $return_data = json_decode($result->httpBody, true);
        $return_data['order_no']=$order_data;
        if ($return_data['alipay_trade_create_response']['code'] == '10000') {
            msg(0, '下单成功请支付', $return_data);
        } else {
            msg(1, $return_data['alipay_trade_create_response']["sub_msg"], $return_data);
        }
    }

    //接送订单发起支付
    public function payDriverOrderAli()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $order_data = Db::name('driver_order')
            ->where('order_no', '=', $order_no)
            ->find();
        if (!$order_data) {
            msg(-1, '订单有误', '');
        }
        $pay_money = $order_data['pay_money'] * 100;
        if (config('site.web_one_price')) {
            $pay_money = 1;
        }
        self::appInit();
        $result = AlipayFactory::util()->generic()
            ->asyncNotify( config('wechat.url').'/payDriverOrderAliBack')
            ->execute(
                'alipay.trade.create',
                [], [
                    'out_trade_no' => $data['order_no'],
                    'total_amount' => round($pay_money / 100, 2),
                    'subject' => '交通服务',
                    'product_code' => 'JSAPI_PAY',
                    'op_app_id' => '2021005100634222',
                    'buyer_open_id' => $this->memberInfo['zfb_open_id'],
                    'op_buyer_open_id' => $this->memberInfo['zfb_open_id']
                ]
            );
        $return_data = json_decode($result->httpBody, true);
        if ($return_data['alipay_trade_create_response']['code'] == '10000') {
            msg(0, '下单成功请支付', $return_data);
        } else {
            msg(1, $return_data['alipay_trade_create_response']["sub_msg"], $return_data);
        }
    }

    //发起套餐支付宝发起支付
    public function payPackageOrderAli()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $order_data = Db::name('package_order')
            ->where('order_no', '=', $order_no)
            ->find();
        if (!$order_data) {
            msg(-1, '订单有误', '');
        }
        $pay_money = $order_data['pay_money'] * 100;
        if (config('site.web_one_price')) {
            $pay_money = 1;
        }
        self::appInit();
        $result = AlipayFactory::util()->generic()
            ->asyncNotify( config('wechat.url').'/packageOrderBackAliBack')
            ->execute(
                'alipay.trade.create',
                [], [
                    'out_trade_no' => $data['order_no'],
                    'total_amount' => round($pay_money / 100, 2),
                    'subject' => '套餐购买',
                    'product_code' => 'JSAPI_PAY',
                    'op_app_id' => '2021005100634222',
                    'buyer_open_id' => $this->memberInfo['zfb_open_id'],
                    'op_buyer_open_id' => $this->memberInfo['zfb_open_id']
//                    'buyer_open_id' => '0651Bp9d8S3AN390gSvm65qSHw24Mcv9HpJF9dWayBYgc0f',
//                    'op_buyer_open_id' => '0651Bp9d8S3AN390gSvm65qSHw24Mcv9HpJF9dWayBYgc0f'
                ]
            );
        $return_data = json_decode($result->httpBody, true);
        if ($return_data['alipay_trade_create_response']['code'] == '10000') {
            msg(0, '下单成功请支付', $return_data);
        } else {
            msg(1, $return_data['alipay_trade_create_response']["sub_msg"], $return_data);
        }
    }

    //发起会员卡支付宝发起支付
    public function payVipOrderAli()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $order_data = Db::name('mcard_order')
            ->where('order_no', '=', $order_no)
            ->find();
        if (!$order_data) {
            msg(-1, '订单有误', '');
        }
        $pay_money = $order_data['pay_money'] * 100;
        if ($order_data['is_car'] == 1) {
            $driver_order = Db::name('driver_order')->where([
                'server_order_id' => $order_data['id']
            ])->find();
            if ($driver_order) {
                $pay_money = ($order_data['pay_money'] + $driver_order['pay_money']) * 100;
            }
        }
        if (config('site.web_one_price')) {
            $pay_money = 1;
        }
        self::appInit();
        $result = AlipayFactory::util()->generic()
            ->asyncNotify(config('wechat.url').'/payVipOrderAliBack')
            ->execute(
                'alipay.trade.create',
                [], [
                    'out_trade_no' => $data['order_no'],
                    'total_amount' => round($pay_money / 100, 2),
                    'subject' => '会员卡购买',
                    'product_code' => 'JSAPI_PAY',
                    'op_app_id' => '2021005100634222',
                    'buyer_open_id' => $this->memberInfo['zfb_open_id'],
                    'op_buyer_open_id' => $this->memberInfo['zfb_open_id']
                ]
            );
        $return_data = json_decode($result->httpBody, true);
        if ($return_data['alipay_trade_create_response']['code'] == '10000') {
            msg(0, '下单成功请支付', $return_data);
        } else {
            msg(1, $return_data['alipay_trade_create_response']["sub_msg"], $return_data);
        }
    }

    //todo 手动回调
    //导诊陪诊订单回调(支付宝)
    public function serverOrderBackAli()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $order_data = Db::name('server_order')
            ->where('order_no', '=', $order_no)
            ->find();
//        if ($order_data['status'] == 1) {
//            serverPaySuccess($order_data, 4);
//        }
        msg(0, "支付成功！", $order_data);
    }

    //接送订单回调(支付宝)
    public function driverOrderBackAli()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $order_data = Db::name('driver_order')
            ->where('order_no', '=', $order_no)
            ->find();
//        if ($order_data['status'] == 1) {
//            driverPaySuccess($order_data, 4);
//        }

        msg(0, "支付成功！", $order_data);
    }

    //购买套餐回调(支付宝)
    public function packageOrderBackAli()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $order_data = Db::name('package_order')
            ->where('order_no', '=', $order_no)
            ->find();
//        if ($order_data['status'] == 1) {
//            //给用户发送套餐
//            $mp_id = giveMemberPackage2($order_data['package_id'], $this->memberId);
//            //更新订单状态
//            $update_package_order = array(
//                'id' => $order_data['id'],
//                'status' => 2,
//                'pay_time' => time(),
//                'fx_money' => getFxMoney($order_data, 3),
//                'mp_id' => $mp_id,
//                'pay_type' => 4
//            );
//            Db::name('package_order')->update($update_package_order);
//            //发送积分
//            addFraction(
//                $this->memberId,
//                $order_data['pay_money'] * config('site.one_price_points'),
//                '套餐订单：' . $order_data['order_no'],
//                3,
//                1,
//                '',
//                '',
//                $order_data['order_no'],
//                3
//            );
//            $this->addFxMoney($order_data, 3);
//        }
        msg(0, "支付成功cccc！", 11);
    }

    //购买会员卡回调(支付宝)
    public function packageVipOrderAli()
    {
        $data = $this->request->param();
        $order_no = $data['order_no'];
        $order_data = Db::name('mcard_order')
            ->where('order_no', '=', $order_no)
            ->find();
//        if ($order_data['status'] == 1) {
//            $mcard_list_id = vip($order_data['mcard_id'], $this->memberId);
//            //更新订单状态
//            $update_mcard_order = array(
//                'id' => $order_data['id'],
//                'status' => 2,
//                'pay_time' => time(),
//                'mcard_list_id' => $mcard_list_id,
//                'fx_money' => getFxMoney($order_data, 4),
//                'pay_type' => 4,
//            );
//            Db::name('mcard_order')->update($update_mcard_order);
//            addFraction(
//                $this->memberId,
//                $order_data['pay_money'] * config('site.one_price_points'),
//                '会员卡订单：' . $order_data['order_no'],
//                3,
//                1,
//                '',
//                '',
//                $order_data['order_no'],
//                4
//            );
//            $this->addFxMoney($order_data, 4);
//        }
        msg(0, "支付成功！", $order_data);
    }

}